November 23, 2014
Hot Topics:

Working with Facebook SDK for JavaScript

  • February 12, 2014
  • By Bipin Joshi
  • Send Email »
  • More Articles »

Introduction

Now-a-days many websites provide Facebook integration to enhance the user experience. Features such as Facebook authentication, displaying Like or comments widgets, posting something on a user's wall are parts of this integration. The Facebook SDK for JavaScript provides functionality that can be consumed from the client side script to leverage such an integration. To that end this article shows you how to implement Facebook authentication, how to retrieve a user's details, such as user name and profile picture, and also illustrates how to post on the user's wall. 

Creating a Facebook App

The first step involved in using the Facebook SDK for JavaScript is to create a Facebook App. The end users subscribe to this app and wall posts (if any) are made on behalf of this application. Creating a Facebook app is a straightforward process. You need to visit https://developers.facebook.com and create an app using the "Create a New App" option. The following figure shows the initial dialog for creating an app.

Create a New App
Create a New App

We won't go into too much detail of the app creation process. All you need to work through the remainder of this article is an App ID - a numeric identifier for a Facebook app to be integrated into your website. You can grab this App ID from the dashboard of the newly created (or existing) app.

Dashboard
Dashboard

The App ID obtained is used during initializtion of the Facebook SDK for JavaScript.

Initialize Facebook SDK for JavaScript

nce you create a Facebook app, create a new website in any development tool of your choice (Visual Studio, for example) and add an HTML page to it. This page will use the Facebook integration features mentioned above. The Facebook SDK for JavaScript is loaded by making an asynchronous call from your web page. To do so, add the following markup in the web page just created:

 <div id="fb-root"></div>

This <div> element is needed by the Facebook SDK for JavaScript to work and must not be hidden. Then add the following JavaScript code inside a <script> block:

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

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

The above code loads the Facebook SDK for JavaScript and initializes it. As you can see, the init() method is used to initialize the SDK and takes a list of configuration parameters. Some of the parameters used by the init() method are listed below:

  • appId : The Facebook App ID. You should replace XXXXXX with the actual ID of your app.
  • status : This Boolean parameter controls whether the current login status of a user is retrieved with each page refresh. If this is set to false you will need to check for the status using getLoginStatus() method.
  • cookie : This Boolean parameter indicates whether a cookie is issued for that session. You can access this cookie in the server side script if necessary.
  • xfbml : This Boolean parameter indicates whether markup of social plugins is parsed (and rendered) or not.

The anonymous function that follows essentially loads the SDK in asynchronous manner. 

Authenticating a User Using Facebook Credentials

Before you can present an integrated experience to the end user, the user must sign-in to Facebook using his/her credentials. To initiate the login process, you will use a button as shown below:

<input type="button" value="Login" onclick="Login();" />

As you can see the Login button invokes the Login() function when a user clicks on it. The Login() function goes inside the <script> block you created earlier and takes the following form:

function Login() {
  FB.login(function (response) {
    if (response.authResponse) {
      // some code here
      };
    } else {
      alert("Login attempt failed!");
    }
  }, { scope: 'email,user_photos,publish_actions' });

}

The Login() function internally calls login() method of the Facebook SDK. The login() method accepts two parameters - a callback function indicating success or failure of the login operation and permissions needed by the Facebook app.

The callback function checks the authResponse parameter and accordingly success or error code is executed. You will add some code inside the if block later. The permissions object specifies three permissions - email address of the user, profile photo of the user and permission to post on behalf of the user. When called, the login() method prompts an OAuth dialog to the end user as shown below:

Login Screen
Login Screen

If this is the first time you are accessing the app, you will also be asked to authorize the app for the requested permissions.

Notifying the User about Authentication Process

Once a user signs in to the Facebook you may need to notify the user of the success or failure, or you may need to do some custom operation when the authentication status changes. This can be done by wiring an event handler for the auth.authResponseChange event. To do so you use the subscribe() method of the Facebook SDK. The following code shows how subscribe() can be used. This code can be placed immediately after the SDK initialization code you wrote earlier.

 FB.Event.subscribe('auth.authResponseChange', function (response) {
  if (response.status === 'connected') {
    alert("Successfully connected to Facebook!");
  }
  else if (response.status === 'not_authorized') {
    alert("Login failed!");
  } else {
    alert("Unknown error!");
  }
});

The first parameter of the subscribe() method indicates the name of an event (auth.authResponseChange in this case) and  the second parameter indicates an event handler in the form of a callback function. The auth.authResponseChange event is raised when the authentication response changes.

The event handler function receives an object that provides some more information about the event under consideration. In the above example, the status property of the response object is used to check the status of authentication. The status property has three possible values viz. connected, not_authorized and unknown. The event handler function displays an appropriate success or error message to the user in an alert dialog.

Retrieving User Information

Once a user is authenticated you can retrieve user details such as user name and user ID. To do so you can use Facebook Graph API as shown below:

function Login() {
  FB.login(function (response) {
    if (response.authResponse) {
      FB.api('/me', function (response) {
        document.getElementById("displayName").innerHTML = response.name;
        document.getElementById("userName").innerHTML = response.username;
        document.getElementById("userID").innerHTML = response.id;
        document.getElementById("userEmail").innerHTML = response.email;
        FB.api('/me/picture?type=normal', function (response) {
          document.getElementById("profileImage").setAttribute("src", response.data.url);
        });
      });
    } else {
      alert("Login attempt failed!");
    }
  }, { scope: 'email,user_photos,publish_actions' });
}

Notice the lines of code marked in bold letters. The code calls a Graph API using the api() method of the SDK. The first parameter of the api() method is path and a value of /me indicates the currently authenticated user. The second parameter indicates a callback function that gets called upon the execution of the API. In the above code, the callback function displays name, username, id and email properties of the response. The name property returns the display name of the user, the username property returns the Facebook user name as it appears in the profile URL. The id property returns the user's numeric ID and the email property returns the user's email address.

Another Graph API call is made to retrieve the user's profile image. The callback function of this API call sets the src attribute of an image element to the response.data.url property, thus displaying the profile photo of the user. The following figure shows the above code in action:

Get User Details
Get User Details

Although hidden in the figure, you should see the user details in the table as explained above.

Posting on a User's Wall

You can post on a user's wall using Graph API. To trigger a post operation add another button to the web page as shown below:

<input type="button" id="postButton" value="Post" onclick="PostMessage();" />

The PostMessage() function calls Graph API like this:

function PostMessage() {
  FB.api('/me/feed', 'post', {
    message: document.getElementById("messageToPost").value
  });
}

As you can see the path parameter is set to /me/feed, the second parameter indicates the method to be used, the third parameter specifies the post content. In this case the content is assumed to be coming from a textarea whose ID is messageToPost.

The following figure shows how a sample post looks like:

Sample Post
Sample Post

If you execute at your end, you will find "test message" is posted on the user's wall via the Facebook App.

Signing Out the User

Signing out is just a matter of calling logout() method of the SDK. To do so, add a button to the web page as shown below:

<input type="button" value="Logout" onclick="Logout();" />

The Logout() function acts as the click event handler for the button and is shown below:

function Logout() {
  FB.logout(function () { document.location.reload(); });
}

The Logout() function simply calls the logout() method of the Facebook SDK. The callback function simply reloads the web page once the user logs out.

Summary

Facebook SDK for JavaScript allows you to integrate many Facebook features in your website. In this article you learned how to authenticate a user using the Facebook SDK. You also learned to retrieve user information such as display name, user name and profile image using Facebook Graph API. The article also illustrated how a message can be posted on the user's wall using the Graph API.


Tags: Facebook, JavaScript, authentication, Facebook API, Facebook apps




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel