Facebook Javascript SDK

Posted: November 25, 2011 in Random Posts
Tags: , ,

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

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.

Loading

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 oauth : true, // enable OAuth 2.0 xfbml : true // parse XFBML }); // Additional initialization code here }; // Load the SDK Asynchronously (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/en_US/all.js"; d.getElementsByTagName('head')[0].appendChild(js); }(document)); </script> 

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

Channel File

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.

Authentication & Authorization

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.

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. The following SDK methods are useful for this purpose:

  • FB.login — log in or request extended permissions
  • FB.logout — log out (only if the user is connected with your application)
  • FB.getLoginStatus — asynchronous method to get the current login status from facebook.com
  • FB.getAuthResponse — synchronous accessor for the current authorization response record, which for connected users includes an access token, a signed request, and a user ID. Only call this method if you have already called getLoginStatus first.

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

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

API Calls

The 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); } ); 

Platform Dialogs

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

See the Platform Dialogs documentation for a full list of available dialogs.

Social Plugins

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

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

Localization

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> 

Synchronous Loading

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 oauth : true, // enable OAuth 2.0 xfbml : true // parse XFBML }); </script> 

Method Categories


Core Methods

Make an API call to the Graph API.

Initialize the library.

Method for triggering Dialogs with Facebook as iframe dialogs or popups. Examples: publishing to the stream, sharing links, sending friend requests.


Auth Methods

Synchronous accessor for the current Session.

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.


Event Handling

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

Removes subscribers, inverse of FB.Event.subscribe.


XFBML Methods

Parse and render XFBML markup in the document.


Data Access Utilities

Performs a parameterized FQL query and returns a FB.Data.query object which can be waited on for the asynchronously fetched data.

Wait until the results of all queries are ready.


Canvas Methods

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.

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.

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.

When using setDoneLoading, controls the page load timer.

When using setDoneLoading, controls the page load timer.

Advertisements
Comments
  1. Helen says:

    I really appreciate this post. I?

  2. […] Facebook Javascript SDK (shanisk.wordpress.com) Share this:TwitterFacebookLike this:LikeBe the first to like this post. This entry was posted in Uncategorized by plantjpc. Bookmark the permalink. […]

  3. ueb sayt says:

    I simply couldn’t leave your web site before suggesting that I extremely enjoyed the usual information a person provide to your guests? Is gonna be again frequently to check up on new posts

  4. Larry Saini says:

    Impressive tips many thanks for posting about it. The truth is in all of content of this web site you will find things to educate yourself on.

  5. Silas Heyen says:

    I became pretty pleased to find this site.I must thanks to this kind of amazing post!! Undoubtedly taking advantage of each sentence of it and i also bookmarked to observe all new infomartion you put up.

  6. Jame Friedman says:

    I wanted to check up and allow you to know how really I cherished discovering this blog today. I’d consider it a good honor to work at my business office and be able to utilize the tips discussed on your web site and also engage in visitors’ remarks like this. Should a position connected with guest writer become offered at your end, remember to let me know.

  7. Juliann Duhamel says:

    Undoubtedly definitely valuable article. With thanks for all your enthusiasm to offer this sort of helpful tips here.

  8. coach credit card holder says:

    Excellent read, I just passed this onto a colleague who was doing some research on that. And he actually bought me lunch because I found it for him smile Thus let me rephrase that: Thank you for lunch!

  9. russian roulette games says:

    I see something really interesting about your web blog so I saved to favorites .

  10. hybrid cars information says:

    Perfectly indited subject material , regards for entropy.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s