India Flag: +91.120.4106935 / 4202026
USA Flag : +1 (804) 591-0052
Logo

LW Employees

Working With Facebook Javascript SDK

loginworks

Working With Facebook Javascript SDK

Posted in technical blogs

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 NamespaceCreating a 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:

 


01

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

02

<
html xmlns="http://www.w3.org/1999/xhtml">

03

<
head>

04

<title>DemoJSApp</title>

05

<script type="text/javascript">

06

window.fbAsyncInit
= function () {

07

FB.init({

08

appId:
'your_app_id', // App ID

09

channelUrl:
'http://localhost:8779/Channel.html',
// Channel File

10

status:
true,

11

cookie:
true, // enable cookies to allow the server to access
the session

12

xfbml:
true // parse XFBML

13

});

14

15

//
Additional init code here

16

};

17

18

//
Load the SDK Asynchronously

19

(function
(d) {

20

var
js, id = 'facebook-jssdk', ref =
d.getElementsByTagName('script')[0];

21

if
(d.getElementById(id)) { return; }

22

js
= d.createElement('script'); js.id = id; js.async =
true;

23

js.src
= "//connect.facebook.net/en_US/all.js";

24

ref.parentNode.insertBefore(js,
ref);

25

}
(document));

26

</script>

27

</
head>

28

<
body>

29

</
body>

30

</
html>

You can know your App’s ID here or on the Basic Settings page of your app.

demo-js-app

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()" />


1

function
login()
{

2

FB.login(function (response)
{

3

if (response.authResponse)
{

4

//
connected

5

} else {

6

//
cancelled

7

}

8

},
{ scope:
'email' });

9

}

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


01

<
body>

02

<
input id="data" type="button" onclick="showData()" value="Show
Data"
/>

03

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

04

<
div id="emailDiv">Your
Email</
div>

05

06

07

Your Friends

08

<
ul>

09

<
li id="friend1">Friend
1</
li>

10

<
li id="friend2">Friend
2</
li>

11

<
li id="friend3">Friend
3</
li>

12

</
ul>

13

</
body>

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


01

window.fbAsyncInit =
function ()
{

02

FB.init({

03

appId: 'your_app_id', //
App ID

04

channelUrl: 'http://localhost:8779/Channel.html',
// Channel File

05

status: true,

06

cookie: true, //
enable cookies to allow the server to access the session

07

xfbml: true //
parse XFBML

08

});

09

10

//
Additional init code here

11

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

12

if (response.status
===
'connected')
{

13

//
connected

14

showInfo();

15

}

16

});

17

18

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

19

20

hideInfo();

21

});

22

};

23

24

// Load the SDK Asynchronously

25

(
function (d)
{

26

var js,
id =
'facebook-jssdk',
ref = d.getElementsByTagName(
'script')[0];

27

if (d.getElementById(id))
{
return;
}

28

js
= d.createElement(
'script');
js.id = id; js.async =
true;

29

js.src
=
"//connect.facebook.net/en_US/all.js";

30

ref.parentNode.insertBefore(js,
ref);

31

} (document));

32

33

function
showInfo()
{

34

FB.api('/me', function (response)
{

35

document.getElementById("emailDiv").innerHTML
= response.email;

36

});

37

38

FB.api('/me/friends',
{ limit: 3 },
function (response)
{

39

document.getElementById("friend1").innerHTML
= response.data[0].name;

40

document.getElementById("friend2").innerHTML
= response.data[1].name;

41

document.getElementById("friend3").innerHTML
= response.data[2].name;

42

});

43

}

44

45

function
hideInfo()
{

46

document.getElementById("emailDiv").innerHTML
=
"Your
Email"
;

47

document.getElementById("friend1").innerHTML
=
"Friend
1"
;

48

document.getElementById("friend2").innerHTML
=
"Friend
2"
;

49

document.getElementById("friend3").innerHTML
=
"Friend
3"
;

50

}

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:


1

FB.api(
'/me?fields=email,friends.limit(3)', function (response)
{

2

document.getElementById("emailDiv").innerHTML
= response.email;

3

document.getElementById("friend1").innerHTML
= response.friends.data[0].name;

4

document.getElementById("friend2").innerHTML
= response.friends.data[1].name;

5

document.getElementById("friend3").innerHTML
= response.friends.data[2].name;

6

});

demojsapp-working-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.


1

FB.getLoginStatus(
function (response)
{

2

if (response.status
===
'connected')
{

3

//
connected

4

showInfo();

5

}

6

});

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 toRSS
feeds
.

give wings to your

business

smart it solutions for the most pressing problems

Leave a Reply

Your email address will not be published. Required fields are marked *

Shares