How to get access token from the url [duplicate] - javascript

This question already has answers here:
Parsing URL hash/fragment identifier with JavaScript
(10 answers)
Closed 7 years ago.
I'm getting this URL after I'm authenticated to Google
http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600
How to get access_token value from this url?
I tried solutions in following urls, none of them are working
How can I get query string values in JavaScript?
How to get the value from the GET parameters?
Using the GET parameter of a URL in JavaScript

Using modern ways, there are better, more reliable ways to get access token field:
var urlString = 'http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600';
var url = new URL(urlString);
// OR: If you want to use the current page's URL
var url = window.location;
var access_token = new URLSearchParams(url.search).get('access_token');
You can also see how this approach makes it easy to get the other parameters in addition. This URLSearchParams approach is supported by all browsers except old instances of IE.
If the above doesn't work (didn't for me) just add 'hash' to window.location, this is also single line code
var access_token = new URLSearchParams(window.location.hash).get('access_token');
Old Answer:
I like RegEx so here's a RegEx answer:
var url = 'http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600',
access_token = url.match(/\#(?:access_token)\=([\S\s]*?)\&/)[1];
access_token is:
ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw
(Directly from the console)
Fiddle

Make use of the URL class in JS:
var token = new URL("http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600").hash.split('&').filter(function(el) { if(el.match('access_token') !== null) return true; })[0].split('=')[1];
alert(token);

Related

Can i use a JS variable as a node in a JSON Stringify Request? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 years ago.
Basically i am trying to grab data from the Bungie API i've been successful up until now. I am trying to read this JSON file. http://prntscr.com/k3tin3
But i'm unsure of how to grab a node from the json then use it to request character data?
This has been my best guess so far and it clearly doesn't work, What am i missing? :/
$.ajax({
url: "https://www.bungie.net/Platform/Destiny2/4/Profile/" + searchField + "/?components=100,200",
headers: {
"X-API-Key": apiKey
}
}).done(function(json){
if(JSON.stringify(json.Response.profile.data.characterIds[0])){
var char_slot_0 = JSON.stringify(json.Response.profile.data.characterIds[0]).replace(/[\"\"]/g, "");
var char_slot_0_class = JSON.stringify(json.Response.characters.data.+ char_slot_0 +.classType);
}
});
Currently grabbing characterIds is working fine, It's the second line i can't get to work. Do i need to make another call instead of doing them in the same call?
Edit: I am trying to use the result variable char_slot_0 which returns: 2305843009303234831. To put as a node in the new json stringify request.
Why are you stringifying the incoming json object? You should be able to access these fields with just the regular property accessor (dot operator). This line var char_slot_0_class = JSON.stringify(json.Response.characters.data.+ char_slot_0 +.classType); looks like invalid javascript.
if(JSON.stringify(json.Response.profile.data.characterIds[0])){
var char_slot_0 = JSON.stringify(json.Response.profile.data.characterIds[0]).replace(/[\"\"]/g, "");
var char_slot_0_class = JSON.stringify(json.Response.characters.data[char_slot_0].classType);
}
After reading a possible duplicate of Dynamically access object property using variable from Heretic Monkey's Comment, I found the solution! Thank you!

Extract values of substring of parameters from string [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
I have a string of the form
p1=v11&p1=v12&p2=v21&p2=v22&p2=v23&p3=v31 and so on
I want to get an array of all values for p2 in javascript, e.g. in this example it would be ["v21", "v22", "v23"].
How do I do it? Do I need to use regex?
You might want to have a look at a JavaScript function I wrote to mimic the $_GET function in PHP:
http://www.martinandersson.com/matooltip/js/ma_GET.js
Google the source code for this line:
returnMe[key] = $.parseJSON( decodeURIComponent(tmpArray[1]) );
The problem with my current implementation is that any old key already stored, will have his value overwritten. What you need to do is to check if the key is already present, if so, read the old value and store him back in an array before you push the new value onto the same array.
The particular line i quoted uses JQuery to make the value into a JavaScript object. If you don't want to use JQuery for this feature then you could use JSON.parse or some other third party library.
Hope it helps, write me a comment if you don't succeed and I'll get back to you.
Try this:
var string = 'p1=v11&p1=v12&p2=v21&p2=v22&p2=v23&p3=v31';
var rawParams = string.split('&');
var params = [];
var param = '';
for (var i in rawParams) {
param = rawParams[i].split('=');
if ('p2' == param[0]) {
params.push(param[1]);
}
}
I don't recommend RegExp here, since the problem is pretty easy to be resolved with one simple for loop.
EDIT:
For sake of any haters - here's the working example: http://jsfiddle.net/j7sY6/1/
For a regex solution:
var matchs = [];
var re = /p2=([^&]+)/g;
while (match = re.exec('p1=v11&p1=v12&p2=v21&p2=v22&p2=v23&p3=v31')) {
matchs.push(match[1]);
}
Output:
matches = ["v21", "v22", "v23"]

Appending query strings from multiple pages

I'm currently stumped on this. I've snooped around for a bit and haven't found any concrete answer using just JS to do this, and so my question is thus. If I am navigating multiple pages and want to keep query strings from the one before attached to the url, what is the easiest way to do this?
You can do this if the way the user "navigates" is by using links within the pages.
In a given html page, Javascript running within the page can see the url's query parameters via the window.search property. Mozilla docs.
Then use JS to modify all of the page's anchor elements' href links to add on the already existing query parameters to the links.
Result: clicking on a link in the page will result in the new page having both the existing and new query parameters.
I don't think there is an easy way. You will have to take in account the current query parameters every time you compose a URL or create a form.
Are you asking for this one?
var url1 = "...", url2 = "...";
var query1 = url1.split("#")[0].split("?").slice(1).join("?");
if (!query1)
return url2;
var parts2 = url2.split("#");
parts2[0] += (parts2[0].indexOf("?")>-1 ? "&" : "?" ) + query1;
return parts2.join("#");
This extracts the query string from url1 and appends it to the query string of url2, returning the new url2.

Grabbing a url variable from a string? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript REGEX: How to get youtube video id from URL?
In javascript I need to grab a url variable that can be the first variable but doesn't have to. The url is a string of a url from Youtube. At first I was using regex to replace everything from & on, but then I found out that the video variable isn't always first. I am not good with regex and just have gone with tutorials I can find and double check to make sure it works right. So I need to be able to grab the v=videoletters part. If I can grab that, I think I can figure from then on to make the normal youtube url which is what I need.
Here's a function that does exactly what you asked for:
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
Found via a Google search on this page: http://www.netlobo.com/url_query_string_javascript.html
So, you would just do:
var videoletters = gup("v");
There are many, many other ways to do this also that you can see via your own search. Here are a few of the others:
How to retrieve query string parameter and values using javascript (Jquery)?
http://www.idealog.us/2006/06/javascript_to_p.html
http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
http://geekswithblogs.net/PhubarBaz/archive/2011/11/21/getting-query-parameters-in-javascript.aspx

Javascript to grab last part of the document.URL? [duplicate]

This question already has answers here:
Last segment of URL with JavaScript
(30 answers)
Closed 12 months ago.
I am trying to grab the last part of the current url:
URL: http://example.com/test/action
I am trying to grab "action".
The URL is always consistent in that structure. But it may have some extra params at the end.
This is in a rails app using the prototype framework. In rails it would be params[:id].
You could simply use .split() on window.location.href, and grab the last entry.
Example:
var lastPart = window.location.href.split("/").pop();
The other answers are fine, however if your url looks like:
http://example.com/test/action?foo=bar
they will fail to give you just "action". To do this you'd use pathname, which contains only the path information exclusive of query string parameters (ie /test/action in this case):
location.pathname.split('/').pop();
use document.location.href.substring( document.location.href.lastIndexOf( '/' ) );
with jquery :
var idFromUrl = window.location.href.split("/").pop();
$('#various3').attr('href', $('#various3').attr('href').replace('placed_id', idFromUrl));
Below is my working javascript solution.Hope it helps some one and hence posting.This solution is to retrieve last part of url leaving the generally not needed query string part.It helps to identify from which page the visit happened and write logic based on that.
var url = document.referrer;
var start = url.lastIndexOf("/") + 1;
var len = url.indexOf("?");
if (len > 0)
url = url.substring(start, len);
else
url = url.substring(start);

Categories

Resources