The JavaScript SDK provides a rich set of client-side functionality for accessing Facebook's server-side API calls. These include all of the features of the REST API, Graph API, and Dialogs. Further, it provides a mechanism for rendering of the XFBML versions of our Social Plugins, and a way for Canvas pages to communicate with Facebook.
You will need an app ID to initialize the SDK, which you can obtain from the App Dashboard.
For example usage, check out Facebook for Websites and the Authentication guide. We also have a JavaScript Test Console which allows you to test and debug common JavaScript SDK methods.
The JavaScript SDK supports OAuth 2.0.
The following code will load and initialize the JavaScript SDK with all common options. Replace YOUR_APP_ID and WWW.YOUR_DOMAIN.COM with the appropriate values. The best place to put this code is right after the opening <body> tag.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization 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>
The JavaScript SDK requires the fb-root element in order to load properly and a call to FB.init to initialize the SDK with your app ID correctly.
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.
This code loads the SDK asynchronously so it does not block loading other elements of your page. This is particularly important to ensure fast page loads for users and SEO robots.
The URLs in the above code are protocol relative. This lets the browser to load the SDK over the same protocol (HTTP or HTTPS) as the containing page, which will prevent "Insecure Content" warnings.
The function assigned to window.fbAsyncInit is run as soon as the SDK is loaded. 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.
The channel file addresses some issues with cross domain communication in certain browsers. The contents of the channel.html file can be just a single line:
<script src="//connect.facebook.net/en_US/all.js"></script>
It is important for the channel file to be cached for as long as possible. When serving this file, you must send valid Expires headers with a long expiration period. This will ensure the channel file is cached by the browser which is important for a smooth user experience. Without proper caching, cross domain communication will become very slow and 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 is optional, but recommended. Providing a channel file can help address three specific known issues. First, pages that include code to communicate across frames may cause Social Plugins to show up as blank without a channelUrl. Second, if no 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. Third, a channel file will prevent inclusion of extra hits in your server-side logs. If you do not specify a channelUrl, you can 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.
The Facebook JavaScript SDK allows your users to register and sign-in to your site using their Facebook accounts. This is done by sharing the logged in user state between facebook.com and your site. A Facebook user remains logged in to your site as long as they are logged in to Facebook and there is a valid access token for your app.
This means you do not need to create your own registration flow and your users do not have to create new profiles or remember a new username. Best of all, you also get to access the user's social graph -- allowing you to create a great customized, social experience and the ability to publish user actions back to Facebook.
In order to use the authentication methods, your app must be configured with an App Domain. App settings can be changed on the settings page.
The first step is figuring out how you identify who the current user is, and how to make API calls on their behalf. The following SDK methods are useful for this purpose:
getLoginStatus first.In addition to the above methods, there are several relevant events that you can subscribe to using FB.Event.subscribe:
auth.loginauth.logoutauth.statusChangeauth.authResponseChangeThe Javascript SDK provides access to our server side APIs. Specifically, they help enable you to integrate data from Facebook into your site, as well as allow you to submit data back to Facebook. The JavaScript SDK makes all this available to you via FB.api.
An example of a Graph API query to get the logged-in user's name:
FB.api('/me', function(response) {
alert('Your name is ' + response.name);
});
If you want to make an FQL query via the legacy REST API:
FB.api(
{
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid=me()'
},
function(response) {
alert('Your name is ' + response[0].name);
}
);
One of the most powerful features of the SDK is to integrate Facebook UI flows into your application. One common example of this is the feed dialog. FB.ui is the method that allows you to trigger this and other dialogs. For example:
FB.ui(
{
method: 'feed',
message: 'getting educated about Facebook Connect',
name: 'Connect',
caption: 'The Facebook Connect JavaScript SDK',
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: 'http://www.fbrell.com/',
picture: 'http://www.fbrell.com/f8.jpg',
actions: [
{ name: 'fbrell', link: 'http://www.fbrell.com/' }
],
user_message_prompt: 'Share your thoughts about RELL'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
See the Platform Dialogs documentation for a full list of available dialogs.
The JavaScript SDK lets you use the XFBML implementations of Social Plugins. Compared to the iframe implementations, XFBML Plugins have additional features and improved performance. In order to use XFBML on your webpage, you must add an XML namespace attribute to the root <html> element of your page. Without this declaration, XFBML tags will not render in Internet Explorer.
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#">
For example, the following code will add a Like button to your page. For more details, see the Like button documentation.
<fb:like send="true" width="450" show_faces="true" />
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 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.
The JavaScript SDK is available in all locales that are supported by Facebook. This list of supported locales is available as an XML file. 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. 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>
It is possible to load the SDK synchronously which may be useful for debugging, but this method is not recommended for typical use. Synchronous operations will block the web page, resulting in worse performance and a slower user experience. This may also negatively impact SEO due to the increased slowness perceived by robots and crawlers.
You can load the SDK using the standard <script> element and calling FB.init afterwards. You must still specify a <div> element named fb-root within the document as well. Below is an example of initializing the SDK with all the common options enabled:
<div id="fb-root"></div>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR_APP_ID',
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
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.
Synchronous accessor for the current Session.
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.
Returns a Javascript object containing information about your app's canvas page.
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.