Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: FB is not defined when using FB.getLoginStatus

I'm trying to check if a user has logged in using facebook and get that error in JS console. My code looks like this:

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function () {
        FB.init({
            appId: '######', // App ID
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true  // parse XFBML
        });
    };

    // Load the SDK Asynchronously
    (function (d) {
        var js, id = 'facebook-jssdk'; if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));

    FB.getLoginStatus(function (response) {
        if (response.status === 'connected') {
            // the user is logged in and has authenticated your
            // app, and response.authResponse supplies
            // the user's ID, a valid access token, a signed
            // request, and the time the access token
            // and signed request each expire
            var uid = response.authResponse.userID;
            var accessToken = response.authResponse.accessToken;
        } else if (response.status === 'not_authorized') {
            // the user is logged in to Facebook,
            // but has not authenticated your app
        } else {
            // the user isn't logged in to Facebook.
        }
    });
</script>

What could be the problem and are there any sugestions on how to fix it?

like image 336
Xeen Avatar asked Feb 28 '13 19:02

Xeen


4 Answers

In Chrome, you'd be getting the error: Uncaught ReferenceError: FB is not defined.

I like to trigger a custom event in Facebook's initialization function, fbAsyncInit(). Then I'm not limited to doing all my FB related scripting inside of the fbAsyncInit function. I can put it anywhere, by just listening for that custom event to be fired.

window.fbAsyncInit = function() {
    FB.init({
        appId      : '123456789',
        status     : true,
        cookie     : true,
        xfbml      : true  
    });

    $(document).trigger('fbload');  //  <---- THIS RIGHT HERE TRIGGERS A CUSTOM EVENT CALLED 'fbload'
};

//MEANWHILE IN $(document).ready()
$(document).on(
    'fbload',  //  <---- HERE'S OUR CUSTOM EVENT BEING LISTENED FOR
    function(){
        //some code that requires the FB object
        //such as...
        FB.getLoginStatus(function(res){
            if( res.status == "connected" ){
                FB.api('/me', function(fbUser) {
                    console.log("Open the pod bay doors, " + fbUser.name + ".");
                });
            }
        });

    }
);
like image 131
jairbow Avatar answered Nov 12 '22 03:11

jairbow


You are calling FB.getLoginStatus before the SDK is loaded and/or initialized. To wait for that, that’s what the fbAsyncInit event is for. So put the method call in there.

like image 31
CBroe Avatar answered Nov 12 '22 02:11

CBroe


I used the following simple approach and it works correctly:

In the head section I load the SDK:

<script type="text/javascript" src="//connect.facebook.net/en_US/sdk.js"></script>

Then in the body of your page where your actual content is, I used this:

<script>

  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    if (response.status === 'connected') {
      testAPI();

    } else if (response.status === 'not_authorized') {
      FB.login(function(response) {
        statusChangeCallback2(response);
      }, {scope: 'public_profile,email'});

    } else {
      alert("not connected, not logged into facebook, we don't know");
    }
  }

  function statusChangeCallback2(response) {
    console.log('statusChangeCallback2');
    console.log(response);
    if (response.status === 'connected') {
      testAPI();

    } else if (response.status === 'not_authorized') {
      console.log('still not authorized!');

    } else {
      alert("not connected, not logged into facebook, we don't know");
    }
  }

  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
  }

  $(document).ready(function() {
    FB.init({
      appId      : '1119999988888898981989819891',
      xfbml      : true,
      version    : 'v2.2'
    });
    checkLoginState();
  });
</script>
like image 10
basZero Avatar answered Nov 12 '22 02:11

basZero


Simply using script with facbook sdk directly in tag

    <script type="text/javascript" src="//connect.facebook.net/en_US/all.js#xfbml=1&appId=YOUR_APP_ID" id="facebook-jssdk"></script>
like image 3
VnDevil Avatar answered Nov 12 '22 04:11

VnDevil