JavaScript Client Library

From Facebook Developer Wiki

Jump to: navigation, search

The Facebook JavaScript client library allows you to access various features of Facebook Platform through JavaScript. You can make Facebook API calls through JavaScript from any website and easily create AJAX Facebook applications. Since the library does not require any server side code, you can now create a Facebook application that can be hosted on any website.

You configure an application that uses this library in one of two ways. You should configure an iframe-based application to load directly, while you should configure an FBML-based application to load through the fb:iframe tag. Users can access iframe-based applications through facebook.com, or directly on the application's own website.

Contents

[edit] Documentation

Documentation of the library is available at JS API Index.

[edit] Features

The JavaScript Client Library features support for the Facebook Platform API as well as usage on iframe canvas pages.

[edit] Facebook API

The library supports most existing Facebook API methods.

Note: Support for the Data Store API is temporarily disabled until we support user-level permissions.

[edit] Canvas Client

If your application is intended to be hosted in an iframe-based canvas page on apps.facebook.com, you can use the FB.CanvasClient.* methods to control the size of the hosting iframe elements. For more information, see Resizable IFrame.

[edit] Setting Up the JavaScript Client

  1. Create a cross domain communication channel to enable communication between your Web site and Facebook.
  2. Reference the FeatureLoader in the page from which you intend to use the library.
    • To reference it from within an iframe canvas page, use the following code:
      <script src="http://static.ak.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>

    • To reference it on a Facebook Connect site, use the following code:
      <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>

      Note: You must include the <script> tag that loads the FeatureLoader in the <body> element (preferably immediately before the </body> tag), not in the <head> element, because the FeatureLoader writes body elements directly to the document, and some browsers report an error if this happens when FeatureLoader is in the <head> tag.
  3. Initialize and load the "features" you require. See Initializing and Loading Facebook Connect Features and FB_RequireFeatures. You need to initialize and load the features you want to use before calling most Facebook Connect API methods.

[edit] Example: Getting a List of a User's Friends (v0.4)

Note: When using v0.4 of the library you have to call FB.Facebook.init() passing your API key and the path to the xd_receiver.htm file. Make sure that your xd_receiver file is referencing the correct version of the library.

Also note that Facebook Connects sites should use FB.Connect.requireSession instead of requireLogin below.

<!-- Text area to display tracing information to the Web page. If you use Firebug or Safari debug console, these tracings will go to the JavaScript console as well. --> <textarea style="width: 1000px; height: 300px;" id="_traceTextBox"> </textarea> <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"> </script> <script type="text/javascript"> //<![CDATA[ var api_key = 'YOUR API KEY'; var channel_path = 'Relative channel path here'; FB_RequireFeatures(["Api"], function(){ // Create an ApiClient object, passing app's API key and // a site relative URL to xd_receiver.htm FB.Facebook.init(api_key, channel_path); var api = FB.Facebook.apiClient; // require user to login api.requireLogin(function(exception){ Debug.dump("Current user id is " + api.get_session().uid); // Get friends list //5-14-09: this code below is broken, correct code follows //api.friends_get(null, function(result){ // Debug.dump(result, 'friendsResult from non-batch execution '); // }); api.friends_get(new Array(), function(result, exception){ Debug.dump(result, 'friendsResult from non-batch execution '); }); }); }); //]]> </script>


This first step of the code calls FB_RequireFeatures() to ensure that the API client feature is loaded. After the API client feature is loaded, it creates an FB.ApiClient object and invokes its requireLogin() method. This step is required before any Platform API calls can be made. Once requireLogin() completes, it invokes the callback function. At that time, you can start calling other API methods. There are two ways to call them: normal mode and batched mode.

In normal mode, you pass a function callback as the last parameter to an API call. When an API method is called, it sends an HTTP request to the Facebook API server. Once the API call is completed, the callback function then gets invoked with the parameters result and exception, where result contains the result of the API call and exception contains any exception information in case of failure.

In batched mode, you can queue up a sequence of individual API calls, then group them all into a single HTTP request to the Facebook server to be executed. Because only a single HTTP request is sent, this could have a substantial performance benefit both on the Facebook API server and in terms of client side latency. To use a batch operation, you need to first create an FB.BatchSequencer object. After creating an FB.BatchSequencer object, it can be passed as the last argument of each individual API call. When you need to execute only batched operations, you can call the execute() method on the FB.BatchSequencer object. Here is some sample code:

/// Example of calling APIs in batched mode //First create a sequencer for batch execution var sequencer = new FB.BatchSequencer(); // By default, individual APIs may be executed in parallel on the server side. // To force sequencial executions on the server, uncomment the following code // sequencer.isParallel = false; //Calling friends_get API, passing the sequencer as last argument var pendingFriendsResult = api.friends_get(null, sequencer); // //Call notifications_get API, passing the sequencer as last argument var pendingNotificationsResult = api.notifications_get(sequencer); //Actually execute the API that is queued inside the sequencer, passing a callback function that is called //when the batch operation is completed. When the callback function is called, the 'result' or 'exception' properties of //pendingFriendsResult and pendingNotificationsResult are updated. sequencer.execute(function() { Debug.dump(pendingFriendsResult.result, 'friendsResult from batch execution'); Debug.dump(pendingNotificationsResult.result, 'notificationsResult from batch execution'); });

[edit] Supported Browsers

The following browsers are currently supported:

  • Internet Explorer 6, 7, 8
  • Firefox 3
  • Safari 3

[edit] Demos

[edit] Authentication Model for the JavaScript API

For this type of application, we settled on the following design objectives:

  1. All Facebook REST API calls require that both the user and application are authenticated and authorized.
  2. After authentication, the session information should be known only by the user, the application, and Facebook.
  3. API calls using this authentication can be used only for operations that read or update user data or perform actions on behalf of the user/app combination. For example, profile.setFBML cannot be used to modify other users' FBML.

For more information, please read the Authentication Model for the JavaScript API.

[edit] Change History

A change history of JavaScript API-related work is available.

reference