How to get access token from the url [duplicate]

2019-04-04 18:16发布

This question already has an answer here:

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

2条回答
Animai°情兽
2楼-- · 2019-04-04 18:35

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

查看更多
叛逆
3楼-- · 2019-04-04 18:53

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

查看更多
登录 后发表回答