Quickstart: Facebook SDK for JavaScript
The Facebook SDK for JavaScript provides a rich set of client-side functionality that:
- Enables you to use the Like Button and other Social Plugins on your site.
- Enables you to use Facebook Login to lower the barrier for people to sign up on your site.
- Makes it easy to call into Facebook's Graph API.
- Launch Dialogs that let people perform various actions like sharing stories.
- Facilitates communication when you're building a game or an app tab on Facebook.
The SDK, social plugins and dialogs work on both desktop and mobile web browsers.
This quickstart will show you how to setup the SDK and get it to make some basic Graph API calls. If you don't want to setup just yet, you can use our JavaScript test console to use all of the SDK methods, and explore some examples (you can skip the setup steps, but the rest of this quickstart can be tested in the console).
Basic Setup
The Facebook SDK for JavaScript doesn't have any standalone files that need to be downloaded or installed, instead you simply need to include a short piece of regular JavaScript in your HTML that will asynchronously load the SDK into your pages. The async load means that it does not block loading other elements of your page.
The following snippet of code will give the basic version of the SDK where the options are set to their most common defaults. You should insert it directly after the opening
<body>
tag on each page you want to load it: <div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '{your-app-id}',
status : true,
xfbml : true
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
This code will load and initialize the SDK. You must replace the value in
appID
with the ID of your own Facebook App. You can find this ID using the App Dashboard.
Notes about the fb-root
tag
The JavaScript SDK requires the
fb-root
element to be present in the page.
The
fb-root
element must not be hidden using display: none
or visibility: hidden
, or some parts of the SDK will not work properly in Internet Explorer.
The SDK inserts elements into
fb-root
which expect to be positioned relative to the body or relative to an element close to the top of the page. It is best if the fb-root
element is not inside of an element withposition: absolute
or position: relative
. If you must place the fb-root
element inside of a positioned element, then you should also give it a position close to the top of the body or some parts of the SDK may not work properly.Using with other SDKs
Our SDK will work alongside other JavaScript libraries. Take a look at our how-tos for a couple of other libraries:
Advanced Setup
As mentioned, the code above uses the common defaults for the options available when initializing the SDK. You can customize some of these options, if useful.
Changing SDK Language
In the basic setup snippet, the
en_US
version of the SDK is initialized, which means that all the dialogs and UI will be in US English. You can change this language by changing the js.src
value in the snippet. Take a look at Localization to see the different locales that can be used. For example, if your site is in Spanish, using the following code to load the SDK will cause all Social Plugins to be rendered in Spanish. <script>
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/es_LA/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
Disabling Login Status Check
By setting
status
to true
in the FB.init()
call, the SDK will attempt to get info about the current user. If they are both logged into Facebook and have granted Facebook Login permission to your app, the SDK will by default return a Login status object on every page load.
Setting
status
to false
can improve page load times, but you'll need to manually check for login status using FB.getLoginStatus. Read on for more about using Facebook Login with the JavaScript SDK.Disabling XFBML Parsing
With
xfbml
set to true
, the SDK will parse your page's DOM to find and initialize any social plugins that have been added using XFBML. If you're not using social plugins on the page, setting xfbml
to false
will improve page load times. You can find out more about this by looking at Social Plugins.Triggering Code when the SDK loads
The function assigned to
window.fbAsyncInit
is run as soon as the SDK has completed loading. Any code that you want to run after the SDK is loaded should be placed within this function and after the call to FB.init
. Any kind of JavaScript can be used here, but any SDK functions must be called afterFB.init
.Debugging
To improve performance, the JavaScript SDK is loaded minified. You can also load a debug version of the JavaScript SDK that includes more logging and stricter argument checking as well as being non-minified. To do so, change the
js.src
value in your loading code to this:js.src = "//connect.facebook.net/en_US/all/debug.js";
More Initialization Options
The reference doc for the
FB.init
function provides a full list of available initialization options.Using the SDK to add Social Plugins
Now that you've got the SDK setup, we can use it to perform a few common tasks. Social Plugins such as the Like Button and Comments Plugin can be inserted into HTML pages using the JavaScript SDK.
Let's try adding a Like button, just copy and paste the line of code below anywhere inside the
<body>
of your page: <div class="fb-like" data-send="true" data-width="450" data-show-faces="true"></div>
Reload your page, and you should see a Like button on it.
Using the SDK to trigger a Feed dialog
The Feed Dialog allows someone using a page to post a link to their timeline, or just simply post a status update. Dialogs displayed using the JavaScript SDK are automatically formatted for the context in which they are loaded - mobile web, or desktop web.
Here we'll show you how the
FB.ui()
method of the SDK can be used to invoke a really basic Feed dialog. Add this snippet after the FB.init()
call in the basic setup code:FB.ui(
{
method: 'feed'
}
);
Now when you reload your page, you'll see a Feed dialog appear over the top of the page. Let's add a few extra parameters to the
FB.ui
call in order to make the Feed dialog more complex: FB.ui(
{
method: 'feed',
name: 'The Facebook SDK for Javascript',
caption: 'Bringing Facebook to the desktop and mobile web',
description: (
'A small JavaScript library that allows you to harness ' +
'the power of Facebook, bringing the user\'s identity, ' +
'social graph and distribution power to your site.'
),
link: 'https://developers.facebook.com/docs/reference/javascript/',
picture: 'http://www.fbrell.com/public/f8.jpg'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
Now when you reload your page, you'll see a Feed dialog again, but this time with more detailed information included in the story that will be created. Once the dialog has been closed, either by posting the story or by cancelling, the response function will be triggered, and you'll see an alert window.
Read the
FB.ui
reference doc to see a full list of parameters that can be used, and the structure of the response object.Using the SDK for Facebook Login
Facebook Login allows users to register or sign in to your app with their Facebook identity.
We have a full guide on how to use the JS SDK to implement Facebook Login. But for now, let's just use some basic sample code, so you can see how it works. Insert the following after your original
FB.init
call:FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.status === 'connected') {
console.log('Logged in');
} else {
FB.login();
}
});
};
Read the Login guide to learn exactly what is happening here, but when you reload your page you should be prompted with the Login dialog for you app, if you haven't already granted it permission.
Using the SDK to call the Graph API
We have another quickstart guide for the Graph API, however here we'll show you how the
FB.api()
method can publish a story on your behalf.
First, we need to get
publish_actions
permission in order to make publishing API calls. So add a line after FB.init
like this:FB.login(function(){}, {scope: 'publish_actions'});
This will trigger a login dialog that'll request the relevant permissions. Next, now that your app can, let's make the API call to publish. Add the API code into the response function of the
FB.login
call you added above:FB.login(function(){
FB.api('/me/feed', 'post', {message: 'Hello, world!'});
}, {scope: 'publish_actions'});
Now, when you reload your page, you'll be asked for permissions (if you haven't granted them already) and then a status message will be posted to your profile:
Congratulations, you should now have learnt how to use the JavaScript to perform a number of common tasks. Dig deeper into the guides linked in each section to learn more about specific methods, or other parts of Facebook Platform.
No comments:
Post a Comment