Check if user is logged in New Facebook API

Here is an example where fbLoginStatus() function will be automatically called when user logs in/logs out, so you can decide which div to display there.

<body>
<div id="fb-root"></div>
<script>
  function fbLoginStatus(response) {
     if( response.status === 'connected' ) {
        //user is logged in, display profile div
     } else {
        //user is not logged in, display guest div
     }
  }
  window.fbAsyncInit = function() {
    FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});
    FB.getLoginStatus(fbLoginStatus);
    FB.Event.subscribe('auth.statusChange', fbLoginStatus);
  };
  (function() {
    var e = document.createElement('script'); e.async = true;
    e.src = document.location.protocol +
      '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
  }());
</script>

Now if you need to check if user is logged in right now (for example on button click):

if(FB.getSession() != null) {
   //logged user id: FB.getSession().uid
} else {
  //user is not logged in
}

Sorry, don’t know any good tutorials.

Leave a Comment