javascript等待子窗口中​​的新页面加载

时间:2012-08-19 07:10:38

标签: javascript oauth

我正在使用javascript进行oAuth。为此我用授权网址打开一个新窗口,然后在这个新窗口中,用户进行身份验证,窗口加载了具有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

请帮助

1 个答案:

答案 0 :(得分: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);