In my Canvas App (tab page) I use this code to get the AccessToken if the app needs it:
var accessToken = "";
FB.getLoginStatus(function (response) {
if (response.authResponse || response.status === 'connected') {
accessToken = response.authResponse.accessToken;
}else {
alert( response.status );
}
} );
return accessToken;
I works fine. BUT if user opens the app and leave it for about 30minutes (or less or more, just for a long time) after this functions can’t get the accessToken just return with an empty string. In the console log there aren’t any error. After if the user refresh the page everything is fine…
What should I do to can get the accessToken anytime?
Here’s what’s going on:
The FB.getLoginStatus method is done asynchronously, and you give it a callback to execute once finished.
In your code you return the
accessTokenright after issuing the async request, but you’re not waiting for it to be completed.It should look like:
So you might ask yourself “so why does it work to begin with?”, the answer is simple: at first the sdk has the authentication data and does not need to actually make the request to the fb servers, as it states in the documentation of the method:
If you try your code with passing `true’, like this:
Then it should not work at all.