Facebook Developers
DocsToolsSupportNewsApps
Log In
  • Getting Started
  • Core Concepts
  • Advanced Topics
  • Technical Guides
  • API Reference
  • SDK Reference
    • JavaScript SDK
    • PHP SDK
    • iOS SDK
    • Android SDK
  • Core Methods
    • FB.api
    • FB.init
    • FB.ui
  • Auth Methods
    • FB.getAuthResponse
    • FB.getLoginStatus
    • FB.login
    • FB.logout
  • Event Handling
    • FB.Event.subscribe
    • FB.Event.unsubscribe
  • XFBML
    • FB.XFBML.parse
  • Canvas Methods
    • FB.Canvas.Prefetcher.addStaticResource
    • FB.Canvas.Prefetcher.setCollectionMode
    • FB.Canvas.getPageInfo
    • FB.Canvas.hideFlashElement
    • FB.Canvas.scrollTo
    • FB.Canvas.setAutoGrow
    • FB.Canvas.setDoneLoading
    • FB.Canvas.setSize
    • FB.Canvas.setUrlHandler
    • FB.Canvas.showFlashElement
    • FB.Canvas.startTimer
    • FB.Canvas.stopTimer

JavaScript SDK

SDK Reference › JavaScript SDK

Overview

The Facebook SDK for Javascript provides a rich set of client-side functionality for letting users Login with Facebook and interacting with Facebook's APIs. This includes calling the Graph API, displaying Dialogs, rendering Social Plugins and interacting with Facebook's parent frame when your app is loaded within a Canvas Page or Page Tab.

  • Loading and Initialization
  • Adding a Channel File
  • Methods

See also:

  • Facebook Login
  • Calling the Graph API
  • Displaying Dialogs
  • Social Plugins
  • Localization
  • Use within Canvas Pages and Page Tabs on Facebook

Loading and Initialization

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. 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 communication
      status     : true, // check the login status upon init?
      cookie     : true, // set sessions cookies to allow your server to access the session?
      xfbml      : true  // parse XFBML tags on this page?
    });

    // Additional initialization code such as adding Event Listeners goes here

  };

  // Load the SDK's source Asynchronously
  // Note that the debug version is being actively developed and might 
  // contain some type checks that are overly strict. 
  // Please report such bugs using the bugs tool.
  (function(d, debug){
     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" + (debug ? "/debug" : "") + ".js";
     ref.parentNode.insertBefore(js, ref);
   }(document, /*debug*/ false));
</script>

Init

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

By default, for performance, the JS SDK is loaded minified. If you are in development and want an un-minified version of the JS SDK, which also enforce arguments in a stricter way, then turn on the debug argument.

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 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

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.

  • Pages that include code to communicate across frames may cause Social Plugins to show up as blank without a channelUrl.
  • 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.
  • a channel file will prevent inclusion of extra hits in your server-side logs. If you do not specify a 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.

Facebook Login

Facebook Login allows users to register or sign in to your app with their Facebook identity. Learn 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 permissions
  • FB.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 user
  • FB.getAuthResponse() — synchronous accessor for the current authorization response record

In addition to the above methods, there are several relevant events that you may subscribe to using FB.Event.subscribe():

  • auth.login
  • auth.logout
  • auth.statusChange
  • auth.authResponseChange

Calling the Graph API

To read or write data to the Graph API, you'll use the JS SDK's FB.api() method.

This simple example reads the currently logged-in users name:

FB.api('/me', function(response) {
  alert('Your name is ' + response.name);
});

Further reading on handling Facebook API errors.

Dialogs

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.');
    }
  }
);

Social Plugins

Social Plugins such as the Like Button and Comments Plugin allow users take lightweight social actions across your site.

Plugins should be embedded in your page with XFBML tags. If you set xfbml: true when calling FB.init() when you initialize the JS SDK, the SDK will search the DOM for any XFBML tags present, and render the correct social plugin in their place.

The following example will add a Like button to your page.

<fb:like send="true" width="450" show_faces="true" />

Note that in order to use XFBML on your page, you must add an fb 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#" >

Localization

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.

Use within Canvas Pages and Page Tabs on Facebook

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.

Custom Flash Hiding Callback

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.


Methods

  • Core Methods
  • Auth Methods
  • Event Handling
  • XFBML
  • Canvas Methods

Core Methods

FB.api

Make an API call to the Graph API.

FB.init

Initialize the library.

FB.ui

Method for triggering Dialogs as popups, modal dialogs or as full pages. The dialogs are automatically formatted for mobile or desktop based on the client.


Auth Methods

FB.getAuthResponse

Synchronous accessor for the current authResponse.

FB.getLoginStatus

Find out the current status from the server, and get a session if the user is connected.

FB.login

Login/Authorize/Permissions.

FB.logout

Logout the user in the background.


Event Handling

FB.Event.subscribe

Subscribe to a given event name, invoking your callback function whenever the event is fired.

FB.Event.unsubscribe

Removes subscribers, inverse of FB.Event.subscribe.


XFBML

FB.XFBML.parse

Parse and render XFBML markup in the document.


Canvas Methods

FB.Canvas.Prefetcher.addStaticResource

Controls which static resources are flushed to the browser early.

FB.Canvas.Prefetcher.setCollectionMode

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.

FB.Canvas.getPageInfo

Returns a Javascript object containing information about your app's canvas page.

FB.Canvas.hideFlashElement

Hides a Flash Element, used in conjunction with hideFlashCallback.

FB.Canvas.scrollTo

Tells Facebook to scroll to a specific location in the iframe of your canvas page.

FB.Canvas.setAutoGrow

Starts or stops a timer which resizes your iframe every few milliseconds.

FB.Canvas.setDoneLoading

Reports that the page is now usable by the user, for collecting performance metrics.

FB.Canvas.setSize

Tells Facebook to resize your iframe.

FB.Canvas.setUrlHandler

Registers the callback for inline processing (i.e. without page reload) of user actions, such as clicks on Live Ticker game stories.

FB.Canvas.showFlashElement

Display a Flash Element, used in conjunction with hideFlashCallback.

FB.Canvas.startTimer

When using setDoneLoading, controls the page load timer.

FB.Canvas.stopTimer

When using setDoneLoading, controls the page load timer.

Updated about 3 weeks ago
Facebook © 2012 · English (US)
AboutAdvertisingCareersPlatform PoliciesPrivacy Policy