0

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.

4

2 回答 2

2

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.

于 2011-07-05T22:45:24.823 回答
1

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

于 2011-07-05T23:43:57.767 回答