javascript 如何从url获取访问令牌
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29934606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get access token from the url
提问by user555
I'm getting this URL after I'm authenticated to Google
我在通过 Google 身份验证后获取此 URL
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?
如何access_token
从此网址获取价值?
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?
采纳答案by Downgoat
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.
您还可以看到这种方法如何使获取其他参数变得更加容易。URLSearchParams
除了旧的 IE 实例之外,所有浏览器都支持这种方法。
If the above doesn't work (didn't for me) just add 'hash' to window.location
, this is also single line code
如果以上不起作用(不适合我),只需将“哈希”添加到window.location
,这也是单行代码
var access_token = new URLSearchParams(window.location.hash).get('access_token');
Old Answer:
旧答案:
I like RegEx so here's a RegEx answer:
我喜欢 RegEx 所以这是一个 RegEx 答案:
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:
access_token
是:
ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw
ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw
(Directly from the console)
(直接从控制台)
Fiddle
小提琴
回答by Stephn_R
Make use of the URL class in JS:
使用 JS 中的 URL 类:
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);