如何从URL获取访问令牌

时间:2015-04-29 04:49:42

标签: javascript jquery url uri

我在通过Google认证

后获取此网址
http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600

如何从此网址获取access_token值?

我在以下网址中尝试了解决方案,其中没有一个正在运行

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

2 个答案:

答案 0 :(得分:12)

我喜欢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是:

  

ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw

(直接来自控制台)

Fiddle

答案 1 :(得分:4)

使用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);