开发者

Getting the Facebook Access Token OUTSIDE of the function

开发者 https://www.devze.com 2023-03-17 18:06 出处:网络
So I am using a function as such to get the access token of the already authenticated user that is currently on my website:

So I am using a function as such to get the access token of the already authenticated user that is currently on my website:

var token;
FB.getLoginStatus(
        function(response){
            if (response.session) { 
                alert(response.session.access_token);
                //This correctly shows the access token. <-----GOOD 
                token = response.session.access_token;
            } 
            else{
                //Other stuff.  
            }
        }
);
alert(token);
//This shows undefined.  <------PROBLEM

The only way to know the access token it seems is to be within the anonymous function called within the call to 开发者_运维问答FB.getLoginStatus.

I have determined that the problem is that the anonymous function inside of FB.getLoginStatus is not executed until the end of all other scripts on the page. Therefore, the variable "token" will not be set until everything is done executing, rendering it useless.

Is there a way then to extract the access token into a universally accessible variable? I don't want to have to write all my code which requires knowledge of the access token in a single anonymous function.


Ye the issue is that the getLoginStatus is an asynchronous call that connects to the FB api. But in the meanwhile your script continues running and so the alert(token); gets called before the getLoginStatus() finished. So the token is not set yet.

I don't know what you want to do exactly with the token, but my way to do this would be to call a function inside the getLoginStatus() as soon as the token has been loaded, and then proceed with the functionality you want. So...

var token;
FB.getLoginStatus(
        function(response){
            if (response.session) { 
                alert(response.session.access_token);
                //This correctly shows the access token. <-----GOOD 
                token = response.session.access_token;
                continueScript();
            } 
            else{
                //Other stuff.  
            }
        }
);


function continueScript() {
      ....
      doSomeMoreFunctionalitiesWithToken();
      ....
}

function doSomeMoreFunctionalitiesWithToken() {
      alert(token);
}

You could for example just show a "loading..." indicator on the screen and only remove it and show the actual content after the getLoginStatus() finished its task and thus after the token has been set.

Hope this helps you.


Try using the expression FB._session.access_token to get the access token from any other location.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号