JavaScript SDK

From Facebook Developer Wiki (FbDevWiki.com)
Jump to: navigation, search

(original documentation)

The JavaScript SDK enables you to access all of the features of the Graph API and Dialogs via JavaScript. It provides a rich set of client-side functionality for authentication and rendering the XFBML versions of our Social Plugins.

Many functions in the JavaScript SDK require an application ID. You can get an app ID by registering your application.

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 SDK is open source and is available on GitHub. Note: this repository appears to be outdated and does not match the current JS that is served from connect.facebook.net. As of 2011-03-29, the last code checkin (non documentation) to github was on 2010-06-15, however the JS served from connect.facebook.net is updated almost weekly. (bug report asking for repository to be updated)


Contents

Usage

You load the SDK using the standard <script> element and calling (FB.init()). You must 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 turned on:

 <div id="fb-root"></div>
 <script src="http://connect.facebook.net/en_US/all.js"></script>
 <script>
   FB.init({
     appId  : 'YOUR APP ID',
     status : true, // check login status
     cookie : true, // enable cookies to allow the server to access the session
     xfbml  : true  // parse XFBML
   });
 </script>

Loading the SDK Asynchronously

The most efficient way to load the SDK in your site is to load it 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/spiders. Below outlines an example:

 <div id="fb-root"></div>
 <script>
   window.fbAsyncInit = function() {
     FB.init({appId: 'your app id', status: true, cookie: true,
              xfbml: true});
   };
   (function() {
     var e = document.createElement('script'); e.async = true;
     e.src = document.location.protocol +
       '//connect.facebook.net/en_US/all.js';
     document.getElementById('fb-root').appendChild(e);
   }());
 </script>

In the example above, the function assigned to window.fbAsyncInit is run as soon as the Facebook JS SDK is loaded. Any code 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 your application is interested in.

Internationalization

The JavaScript SDK supports different locales. You can replace the en_US locale specified in the above example with one of the supported Facebook Locales. For example, to load up the SDK and render dialogs, etc. in Hindi (hi_IN), you can load the SDK from:

http://connect.facebook.net/hi_IN/all.js

Currently Facebook does not tell you what language is being used when a person views your application/website. Once they have authorized your application, you can do a query to see what language they have set, but before authorization there's no way to tell. If your application is multi-lingual, you may want to try using http-negotiate-language (if you're coding in PHP) before the user has authorized the application to try to show the proper language. For other programming languages you should be able to find some functions to read the Accept-Language HTTP header and determine which language to use.

SSL

Facebook Connect is also available over SSL. You should only use this when your own page is served over https://. The library will rely on the current page protocol at runtime. The SSL URL is the same, only the protocol is changed:

https://connect.facebook.net/en_US/all.js

Debugging

In order to help with debugging, we provide a debug version of the SDK (available for the en_US locale only):

http://static.ak.fbcdn.net/connect/en_US/core.debug.js

Authentication & Authorization

The Facebook JavaScript SDK allows you to remove user registration and sign-in by allowing the user to login to your site with their Facebook account. This is achieved by sharing the logged in user state between http://www.facebook.com/ and your site. A Facebook user remains logged in to your site as long as they are logged in to Facebook.

This means you do not need to create your own registration flow, your user's 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 great a great customized, social experience.

Status & Sessions

The first step is figuring out how you identify who the current user is, and how to make API calls on their behalf. In fact, almost half of the public API deals directly with auth:

In addition, there many events that you can subscribe to using FB.Event.subscribe():

  • auth.statusChange
  • auth.sessionChange
  • auth.login
  • auth.logout

API Calls

Facebook provides many server-side APIs to enable you to integrate data from Facebook into your site, as well as allowing you to submit data into Facebook. The JavaScript SDK makes all this available to you via FB.api:

FB.api(
  {
    method: 'fql.query',
    query: 'SELECT name FROM user WHERE uid=5526183'
  },
  function(response) {
    alert('Name is ' + response[0].name);
  }
);

Dialogs

One of the most powerful features of the SDK is to integrate Facebook UI flows into your application. The most common example of this is the stream.publish dialog. FB.ui is the method that allows you to trigger this and other dialogs. For example:

FB.ui(
  {
    method: 'stream.publish',
    attachment: {
      name: 'JSSDK',
      caption: 'The Facebook 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.'
      ),
      href: 'http://fbrell.com/'
    },
    action_links: [
      { text: 'fbrell', href: 'http://fbrell.com/' }
    ]
  },
  function(response) {
    if (response && response.post_id) {
      alert('Post was published.');
    } else {
      alert('Post was not published.');
    }
  }
);

SDK Components

Data Types

FB.Array
array related helper methods useful with FB.Data.query

Core Methods

FB.ui
Method for triggering UI interaction with Facebook as iframe dialogs or popups, like publishing to the stream, sharing links.
FB.getSession
Synchronous accessor for the current Session.
FB.logout
Logout the user in the background.
FB.getLoginStatus
Find out the current status from the server, and get a session if the user is connected.
FB.init
Initialize the library.
FB.login
Login/Authorize/Permissions.
FB.api
Make an API call to the Graph API or the old REST.

Event Handling

FB.Event.unsubscribe
Removes subscribers, inverse of FB.Event.subscribe.
FB.Event.subscribe
Subscribe to a given event name, invoking your callback function whenever the event is fired.

XFBML Methods

FB.XFBML.parse
Parse and render XFBML markup in the document.

Data Access Utilities

FB.Data.waitOn
Wait until the results of all queries are ready.
FB.Data.query
Performs a parameterized FQL query and returns a FB.Data.query object which can be waited on for the asynchronously fetched data.

Canvas Methods

FB.Canvas.getPageInfo
FB.Canvas.scrollTo
FB.Canvas.setAutoGrow (was FB.Canvas.setAutoResize)
Starts or stops a timer which resizes your iframe every few milliseconds.
FB.Canvas.setDoneLoading
Allows you to report to Facebook when a page finished loading to see the page loading performance under "Performance" in Facebook Insights
FB.Canvas.setSize
Tells Facebook to resize your iframe.
FB.Canvas.startTimer
FB.Canvas.stopTimer

CanvasInsights Methods

FB.CanvasInsights.setDoneLoading
Alias function for FB.Canvas.setDoneLoading

More Examples

Lots of great examples: http://fbrell.com/examples

Personal tools
Namespaces
Variants
Actions
Navigation
Graph API
FQL
Toolbox