In this guide:
fb-root tagThe Facebook SDK for JavaScript provides a rich set of client-side functionality that:
The SDK works on both desktop and mobile web browsers and is about 59kB compressed.
The following code will load and initialize the JavaScript SDK with the most common options. Replace YOUR_APP_ID and WWW.YOUR_DOMAIN.COM with the appropriate values from the App Dashboard.
This code should be placed directly after the opening <body> tag.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : 'YOUR_APP_ID', // App ID from the app dashboard
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK asynchronously
(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>
Using the method above, the JS SDK is loaded asynchronously so it does not block loading other elements of your page. The function assigned to window.fbAsyncInit is run as soon as the SDK source has finished 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. For example, this is where you would test the logged in status of the user or subscribe to any Facebook events in which your application is interested.
See the FB.init documentation for a full list of available initialization options.
fb-root tagThe 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 with position: 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.
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>
The channel file should be set to be cached for as long as possible. When serving this file, you should send valid Expires headers with a long expiration period. This will ensure the channel file is cached by the browser and not reloaded with each page refresh. Without proper caching, users will suffer a severely degraded experience. A simple way to do this in PHP is:
<?php
$cache_expire = 60*60*24*365;
header("Pragma: public");
header("Cache-Control: max-age=".$cache_expire);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$cache_expire) . ' GMT');
?>
<script src="//connect.facebook.net/en_US/all.js"></script>
The channelUrl parameter within FB.init() is optional, but strongly recommended. Providing a channel file can help address three specific known issues.
channelUrl. channelUrl is provided and a page includes auto-playing audio or video, the user may hear two streams of audio because the page has been loaded a second time in the background for cross domain communication. channelUrl, you should remove page views containing fb_xd_bust or fb_xd_fragment parameters from your logs to ensure proper counts.The channelUrl must be a fully qualified URL matching the page on which you include the SDK. In other words, the channel file domain must include www if your site is served using www, and if you modify document.domain on your page you must make the same document.domain change in the channel.html file as well. The protocols must also match. If your page is served over https, your channelUrl must also be https. Remember to use the matching protocol for the script src as well. The sample code above uses protocol-relative URLs which should handle most https cases properly.
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 unminified. To do so, change the URL you load to this:
js.src = "//connect.facebook.net/en_US/all/debug.js";
The JavaScript SDK is available in all locales that are supported by Facebook.
To change the locale of the SDK to match the locale of your site, change en_US to a supported locale code when loading the SDK's source. 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>
Note that if you use a Channel File, you should also change the URL to match the URL from which you load the JS SDK on your main pages.
Social Plugins such as the Like Button and Comments Plugin allow users to take lightweight social actions across your site.
They are embedded in your web page with special-named tags. They can be specified in one of two formats.
HTML5 style (preferred):
<div class="fb-like" data-send="true" data-width="450" data-show-faces="true"></div>
Or XHTML style:
<html xmlns:fb="http://ogp.me/ns/fb#">
...
<fb:like send="true" width="450" show_faces="true"></fb:like>
The SDK will automatically scan your page for either of these style of tags if you set xfbml: true in the options you pass into FB.init() and set up the plugin for you.
You can leave xfbml to false if you don't have any social plugins on your page to improve performance.
Facebook Dialogs provide a simple way to provide functionality such as sharing content to a users timeline, taking payments, sending messages and sending requests. To display a dialog, you'll use the JS SDK's FB.ui() method.
Dialogs displayed with the JS SDK are automatically formatted for the context in which they are loaded - mobile web, or desktop web.
The following example uses the FB.ui() method to invoke the Feed Dialog to allow a user to post a link to their timeline:
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.');
}
}
);
Facebook Login allows users to register or sign in to your app with their Facebook identity.
We have a larger guide on how to use the JS SDK to implement Facebook Login.
The JS SDK methods you will use when implementing Facebook Login include:
FB.login() — ask the user to login or request additional permissionsFB.logout() — log the user out (only if the user has authorized your application)FB.getLoginStatus() — asynchronous method to get the current Facebook login status of the userIn addition to the above methods, there are several relevant events that you may subscribe to using
FB.Event.subscribe():
auth.loginauth.logoutauth.statusChangeauth.authResponseChangeTo read or write data to the Graph API, you'll use the JS SDK's FB.api() method.
We have a larger guide on getting started with the Graph API.
This simple example reads the currently logged-in users name:
FB.api('/me', function(response) {
alert('Your name is ' + response.name);
});
The JavaScript SDK provides a way for Canvas pages on Facebook to communicate with the parent facebook.com page. This is useful for resizing the Canvas iframe, collecting performance data, and optimizing static resources. For more information see the Apps on Facebook guide.
A special consideration for Flash Developers on Canvas - if you are hosting an Adobe Flash Application it is recommended that you set the wmode of the Flash object to opaque.
If you must use wmode values of window or direct, Canvas will automatically hide and display the Flash object when Dialogs, Ticket flyouts, Chat Tabs and Notifications display.
Developers who wish to provide a custom hide and display experience may pass a JavaScript function in the hideFlashCallback option for FB.init. This function will be executed whenever the Flash object is hidden or displayed due to user behavior (clicking on a Notification, etc.) and can be used by a developer to take the appropriate actions: hiding or displaying their Flash object. It receives a parameter of type object that contains two properties:
state |
Supports values: 'opened' or 'closed'. |
elem |
The HTML element that will be hidden or displayed. |
The custom action must complete within 200ms or the Flash object will be hidden automatically regardless.
Sample implementation:
function(params) {
if (params.state == 'opened') {
// Hide the Flash object
FB.Canvas.hideFlashElement(params.elem);
} else {
// Display the Flash object
FB.Canvas.showFlashElement(params.elem);
}
As displayed in the example above, Flash content can be manually hidden and displayed via FB.Canvas.hideFlashElement and FB.Canvas.showFlashElement.
Initialize the library.
Synchronous accessor for the current authResponse.
Find out the current status from the server, and get a session if the user is connected.
Login/Authorize/Permissions.
Logout the user in the background.
Subscribe to a given event name, invoking your callback function whenever the event is fired.
Removes subscribers, inverse of FB.Event.subscribe.
Parse and render XFBML markup in the document.
Controls which static resources are flushed to the browser early.
Controls how statistics are collected on resources used by your application, with the intent to influence whether those resources will be fetched to the browser early, or to turn off Prefetching completely.
Hides a Flash Element, used in conjunction with hideFlashCallback.
Tells Facebook to scroll to a specific location in the iframe of your canvas page.
Starts or stops a timer which resizes your iframe every few milliseconds.
Reports that the page is now usable by the user, for collecting performance metrics.
Tells Facebook to resize your iframe.
Registers the callback for inline processing (i.e. without page reload) of user actions, such as clicks on Live Ticker game stories.
Display a Flash Element, used in conjunction with hideFlashCallback.
When using setDoneLoading, controls the page load timer.
When using setDoneLoading, controls the page load timer.