1

我正在使用 javascript 进行 oAuth。为此,我打开一个带有授权 url 的新窗口,然后在这个新窗口中用户进行身份验证,并且该窗口加载了具有 access_token 的页面。

现在我想从原始窗口访问这个令牌。所以基本上我想等到用户授权并且在打开的窗口中加载新页面(带有 access_token),然后访问它。如何做到这一点

authWin=window.open('https://login.salesforce.com/services/oauth2/authorize?   response_type=token&client_id=3MVG9Y6d_Btp4xp4VNFwdCLxJdMbnQrg44lVcvrLG5Qjp3serQQunkCgdS1bYXMSYDQhiSWazvF_J7oVZ9dBw&redirect_uri=sfdc://success','','width=500,height=300');

//code which is not working
while(true){
    var uri = authWin.document.URL;
    if(uri.indexOf('AuthorizationPage')!=-1){
       alert('now I can get access_token');
       break;
    }
 }
 //I know while(true) locks the system,but please provide alternative for this

请帮忙

4

1 回答 1

0

您可以使用 setInterval() 执行此操作

var timerId = setInterval(function () {

            if (typeof(authWin.opener) === 'object') { //if user closed authWin stop awaiting auth
                try {
                    var tokenUri = authWin.location.pathname; //this throwing a error while user not on the same domain(see "same origin policy"), we catch exception and processing like awaiting user back
                    clearInterval(timerId); //when user get back after remote auth on our domain we again have access to authWin properties

                    var token = tokenUri.replace(/\/#access_token=(.+?)&.+/, '$1'); //parsing token from uri
                    authService.saveAuthToken(token);
                    authWin.close();

                    //do something ...
                }
                catch (err) {
                    console.log('waiting for user back');
                }
            }
            else {
                clearInterval(timerId);
            }

        }, 2000);
于 2015-12-23T08:22:49.117 回答