12:34 pm
March 12
Working with Facebook Javascript SDK
( 2 Votes )
Written by: Rohan Makkar Views : 5343

Integrating Facebook within your website not only increases traffic but also makes your site more social and tailored to the user's taste. The result of this social integration would be much more than the hard work you put in. Steps below are no different from Facebook Docs but are presented much more cleanly and from a beginners point of view.

1. Creating a Facebook App

The first and foremost step is to create a Facebook app. It's easy and would not take more than five minutes.

i) Visit https://developers.facebook.com/apps and create a new app
ii) Fill in the desired App Name and Namespace
create-facebook-app

iii) In the section 'Select how your app integrates with Facebook' choose 'Website with Facebook Login'
vi) Enter your website URL in the 'Site URL' field. Remember to add a trailing '/'

2. Setting up Javascript SDK

Here's my blank HTML page with SDK setup:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>DemoJSApp</title>
    <script type="text/javascript">
        window.fbAsyncInit = function () {
            FB.init({
                appId: 'your_app_id', // App ID
                channelUrl: 'http://localhost:8779/Channel.html', // Channel File
                status: true,
                cookie: true, // enable cookies to allow the server to access the session
                xfbml: true  // parse XFBML
            });

            // Additional init code here
        };

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

You can know your App's ID here or on the Basic Settings page of your app.
demojsapp-basic-settings-facebook

If cookie set to true, the SDK stores the access_token in cookies and let's you to make API calls without specifying a access_token as it's directly accessed by Facebook's server. What is Channel.html? Why do I need it? Answer straight from Facebook:

Adding a Channel File greatly improves the performance of the JS SDK by addressing issues with cross-domain communication in certain browsers. The contents of the channel.html file should be just a single line:
<script src="//connect.facebook.net/en_US/all.js"></script>

You can learn more about Channel file here.

3a Connect through Facebook Login Button

Facebook provides a easy to use Login Button for external websites. You can choose the plugin's size from small, medium, large, xlarge, by default medium is selected. One of the parameters, show-faces if set to true, shows profile pictures of the user's friends who have already signed up for your site.  You can get your customized Login Button here. Here's what I get for myself:

<div class="fb-login-button" data-show-faces="false" data-width="200" data-max-rows="1"></div>

Once the user logs in, the Login Button gets hidden and only profile pictures are visible (ofcourse, if show-faces was set to true). I have set show-faces to false, as I know no one except me would be using this app. There is another very important option 'AutoLogoutLink' which is undocumented for an unknown reason. Having AutoLogoutLink to true turns the text of Login Button to Logout and allows users to logout of their Facebook session.

<div class="fb-login-button" autologoutlink="true" data-show-faces="false" data-width="200" data-max-rows="1" size="medium">

If you need to access information apart from the user's basic info, you can add those permissions in the scope parameter.

<div class="fb-login-button" autologoutlink="true" data-show-faces="false" data-width="200" data-max-rows="1" size="medium" scope="email">

3b Connect without Facebook Login Button

If you have a very different color scheme for your website and can't incorporate the Facebook's blue button, you can allow users to connect with your website through your own custom button.

<input id="button1" type="button" value="Log In" onclick="login()" />

  function login() {       
            FB.login(function (response) {              
                if (response.authResponse) {
                    // connected                    
                } else {
                    // cancelled
                }
            }, { scope: 'email' });
        }

4 Making calls to API

Once the user is connected with our app, we can make API calls and access user information. Here's is what I have for layout:
demojsapp-interface-facebook

<body>
<input id="data" type="button" onclick="showData()" value="Show Data"/>
<div class="fb-login-button" autologoutlink="true" data-show-faces="false" data-width="200" data-max-rows="1" size="medium" scope="email"></div>
<div id="emailDiv">Your Email</div>
<br />
Your Friends
<ul>
<li id="friend1">Friend 1</li>
<li id="friend2">Friend 2</li>
<li id="friend3">Friend 3</li>
</ul>
</body>

You can subscribe to auth.Login event to be notified when user's auth status changes from unknown to connected and vice-versa for auth.logout event. Here's updated Javascript block:

window.fbAsyncInit = function () {
    FB.init({
        appId: 'your_app_id', // App ID
        channelUrl: 'http://localhost:8779/Channel.html', // Channel File
        status: true,
        cookie: true, // enable cookies to allow the server to access the session
        xfbml: true  // parse XFBML
    });

    // Additional init code here
    FB.Event.subscribe('auth.login', function (response) {
        if (response.status === 'connected') {
            // connected                    
            showInfo();
        }
    });

    FB.Event.subscribe('auth.logout', function (response) {

        hideInfo();
    });
};

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

function showInfo() {
    FB.api('/me', function (response) {
        document.getElementById("emailDiv").innerHTML = response.email;
    });

    FB.api('/me/friends', { limit: 3 }, function (response) {
        document.getElementById("friend1").innerHTML = response.data[0].name;
        document.getElementById("friend2").innerHTML = response.data[1].name;
        document.getElementById("friend3").innerHTML = response.data[2].name;
    });
}

function hideInfo() {
        document.getElementById("emailDiv").innerHTML = "Your Email";
        document.getElementById("friend1").innerHTML = "Friend 1";
        document.getElementById("friend2").innerHTML = "Friend 2";
        document.getElementById("friend3").innerHTML = "Friend 3";            
}

The showInfo method make calls to Facebook Graph API and extract user's email id and friends. Here me refers to the currently logged in user. I have limted the friends count to 3, you can get the list of all friends by removing the limit clause. You can also merge the two API calls into one, like:

  FB.api('/me?fields=email,friends.limit(3)', function (response) {
                document.getElementById("emailDiv").innerHTML = response.email;
                document.getElementById("friend1").innerHTML = response.friends.data[0].name;
                document.getElementById("friend2").innerHTML = response.friends.data[1].name;
                document.getElementById("friend3").innerHTML = response.friends.data[2].name;
            });

facebook-javascript-sdk

5 User Status on Page Load

Suppose the user is already logged in to Facebook and had also granted the permissions you asked earlier. Now when he/she visits your app the Login Button will show that user is logged in and there would be no way for user to Login again in your app and you will never be notified for auth.login event. You can overcome this problem by using FB.getLoginStatus.

  FB.getLoginStatus(function (response) {
                if (response.status === 'connected') {
                    // connected                    
                    showInfo();
                }
            });

I have added it with the other event subscriptions (i.e within intialization SDK), this lets us know whether the user is already connected or not on the page load. However, you can call it anytime to know the user's connection status.

Next Part: Publish Actions With Facebook Javascript SDK

I hope this guide helped you in getting started with SDK. Don't forget to visit our Facebook page and subscribe to RSS feeds.



Integrating Facebook into your website through Javascript SDK and making Graph API calls.
( 2 Votes )