Search code examples
facebookfacebook-graph-apimobile-websitefacebook-authenticationmobile-browser

FB.login not triggering in mobile browsers


I'm building a mobile web site that directs users through Facebook auth with the following code

(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {
        return;
    }
    js = d.createElement(s);
    js.id = id;
    js.src = "//connect.facebook.net/en_US/all.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

window.fbAsyncInit = function () {
    FB.init({
        appId: '{app_id}', // App ID from the app dashboard
        channelUrl: '{app url}', // Channel file for x-domain comms
        status: true, // Check Facebook Login status
        xfbml: true
    });

    FB.login(function (response) {
    //FB.login contents
    }, {
        scope: '{permissions}'
    });
}

This works on desktop browsers but in mobile browsers FB.login doesn't trigger. It seems many people have had this issue. According to this Stack Exchange question FB.login cannot be fired inside window.fbAsyncInit and the best way around the issue is to have a button that triggers FB.login once everything is loaded. Can someone authoritative verify that this is my best option before I implement it.


Solution

  • The best approach is to use FB.getLoginStatus instead FB.login in fbAsyncInit part, and then based on the current status you can sign in user, or use his credentials. Got something like this:

    window.fbAsyncInit = function () {
        FB.Event.subscribe('auth.statusChange', function(auth){
            if(auth.status==='connected'){
                // subscribe to event, and do some magic stuff when status changes
            }
        });
    
        FB.init({
            appId: fb_config_app_id,        // App ID from the app dashboard
            channelUrl: fb_config_channel,  // Channel file for x-domain comms
            status: true,                   // Check Facebook Login status
            xfbml: true                     // Look for social plugins on the page
        });
    
        // Load in the user credentials
        FB.getLoginStatus(function(response){
            if (response.status === 'connected') {
                // hey - user is already connected !
            } else {
                // login user
            }
        });
    }