Can you call FB.login inside a callback from other FB methods (like FB.getLoginStatus) without triggering popup blockers?
- by Erik Kallevig
I'm trying to set up a pretty basic authentication logic flow with the FB JavaScript SDK to check a user's logged-in status and permissions before performing an action (and prompting the user to login with permissions if they are not)...
User types a message into a textarea on my site to post to their
Facebook feed and click's a 'post to facebook' button on my site.
In response to the click, I check user's logged in status with FB.getLoginStatus
In the callback to FB.getLoginStatus, if user is not logged in,
prompt them to login (FB.login).
In the callback to FB.login I then
need to make sure they have the right permissions so I make a call
to FB.api('/me/permissions') -- if they don't , I again prompt them
to login (FB.login)
The problem I'm running into is that anytime I try to call FB.login inside a callback to other FB methods, the browser seems to lose track of the origin of execution (the click) and thus will block the popup. I'm wondering if I'm missing some way to prompt the user to login after checking their status without the browser mistakenly thinking that it's not a user-initiated popup?
I've currently fallen back to just calling FB.login() first regardless. The undesired side effect of this approach, however, is that if the user is already logged-in with permissions and I'm still calling FB.login, the auth popup will open and close immediately before continuing, which looks rather buggy despite being functional.
It seems like checking a user's login status and permissions before doing something would be a common flow so I feel like I'm missing something. Here's some example code.
<div onclick="onClickPostBtn()">Post to Facebook</div>
<script>
// Callback to click on Post button.
function onClickPostBtn() {
// Check if logged in, prompt to do so if not.
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
checkPermissions(response.authResponse.accessToken);
} else {
FB.login(function(){}, {scope: 'publish_stream'})
}
});
}
// Logged in, check permissions.
function checkPermissions(accessToken) {
FB.api('/me/permissions',
{'access_token': accessToken},
function(response){
// Logged in and authorized for this site.
if (response.data && response.data.length) {
// Parse response object to check for permission here...
if (hasPermission) {
// Logged in with permission, perform some action.
} else {
// Logged in without proper permission, request login with permissions.
FB.login(function(){}, {scope: 'publish_stream'})
}
// Logged in to FB but not authorized for this site.
} else {
FB.login(function(){}, {scope: 'publish_stream'})
}
}
);
}
</script>