The reason why you want to connect your web pages to Facebook is, of course, either to get user related data from Facebook (such getting the user's Facebook profile, his/her friend list) or to post data to Facebook on behalf of the user (e.g. publishing post to the user's Wall).

No matter what you want to do, it is very likely that the first thing you need to do is to check whether the user is connected with your application / web site or not.

Note:

To check if a user is connected or not, we call use the method FB.getLoginStatus or FB.getSession.

 

Checking if the User is Connected or not - FB.getLoginStatus

Sample code for performing the checking by using FB.getLoginStatus is shown below:

FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know alert('Welcome! Facebook user.');
} else {
// no user session available, someone you dont know alert('Who are you?');
}
});

 

Checking if the User is Connected or not - FB.getSession

The equivalence of the above coding using FB.getSession is:

  window.fbAsyncInit = function() {
    FB.init({appId  : '134893243199526', status : true, cookie : true, xfbml : true });
	
    session = FB.getSession();
if (session) {
alert('Welcome! Facebook user.');
} else {
alert('Who are you?');
};
};

 

FB.getLoginStatus vs. FB.getSession

While there are 2 methods that we can use to check the user status, so what are the differences?

Testing to be Done

As an exercise, let's try to implement the following code in the "Welcome (Async)" page.

  window.fbAsyncInit = function() {
    FB.init({appId  : '134893243199526', status : true, cookie : true, xfbml : true });
	
    FB.getLoginStatus(function(response) {
      alert(response.status);
      if (response.session) {
        alert('Welcome! Facebook user.');
} else { alert('Who are you?');
} }); };

Then perform the following test cases:

If you pay attention to what pop messages are displayed in the above scenarios, you should understand the difference between "connected", "notConnected" and "unknown" and also understand when a valid session will be returned from FB.getLoginStatus.

Now, replace the above code segment by the one using FB.getSession. Repeat the above test cases and when will you get a session. Pay attention to the 3rd test case and try to reload the page once more.

 

If you want to know more about these 2 methods, please kindly refer to the official JavaScript SDK Documentation.