Facebook SDK API

Fuente: https://developers.facebook.com/docs/javascript/quickstart/v2.3

Quickstart: Facebook SDK for JavaScript

The Facebook SDK for JavaScript provides a rich set of client-side functionality that:

  • Enables you to use the Like Button and other Social Plugins on your site.
  • Enables you to use Facebook Login to lower the barrier for people to sign up on your site.
  • Makes it easy to call into Facebook’s Graph API.
  • Launch Dialogs that let people perform various actions like sharing stories.
  • Facilitates communication when you’re building a game or an app tab on Facebook.

The SDK, social plugins and dialogs work on both desktop and mobile web browsers.

This quickstart will show you how to setup the SDK and get it to make some basic Graph API calls. If you don’t want to setup just yet, you can use our JavaScript test console to use all of the SDK methods, and explore some examples (you can skip the setup steps, but the rest of this quickstart can be tested in the console).

Basic Setup

The Facebook SDK for JavaScript doesn’t have any standalone files that need to be downloaded or installed, instead you simply need to include a short piece of regular JavaScript in your HTML that will asynchronously load the SDK into your pages. The async load means that it does not block loading other elements of your page.

The following snippet of code will give the basic version of the SDK where the options are set to their most common defaults. You should insert it directly after the opening <body> tag on each page you want to load it:

      window.fbAsyncInit = function() {
          appId      : 'your-app-id',
          xfbml      : true,
          version    : 'v2.3'

      (function(d, s, id){
         var js, fjs = d.getElementsByTagName(s)[0];
         if (d.getElementById(id)) {return;}
         js = d.createElement(s); js.id = id;
         js.src = "//connect.facebook.net/en_US/sdk.js";
         fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));

This code will load and initialize the SDK. You must replace the value in your-app-id with the ID of your own Facebook App. You can find this ID using the App Dashboard.

Advanced Setup

As mentioned, the code above uses the common defaults for the options available when initializing the SDK. You can customize some of these options, if useful.

Changing SDK Language

In the basic setup snippet, the en_US version of the SDK is initialized, which means that all of the Facebook-generated buttons and plugins used on your site will be in US English. (However, pop-up dialogs generated by Facebook like the Login Dialog will be in the language the person has chosen on Facebook, even if they differ from what you’ve selected.) You can change this language by changing the js.src value in the snippet. Take a look at Localization to see the different locales that can be used. 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.

      (function(d, s, id){
         var js, fjs = d.getElementsByTagName(s)[0];
         if (d.getElementById(id)) return;
         js = d.createElement(s); js.id = id;
         js.src = "//connect.facebook.net/es_LA/sdk.js";
         fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));

Login Status Check

If you set status to true in the FB.init() call, the SDK will attempt to get info about the current user immediately after init. Doing this can reduce the time it takes to check for the state of a logged in user if you’re using Facebook Login, but isn’t useful for pages that only have social plugins on them.

You can use FB.getLoginStatus to get a person’s login state. Read on for more about using Facebook Login with the JavaScript SDK.

Disabling XFBML Parsing

With xfbml set to true, the SDK will parse your page’s DOM to find and initialize any social plugins that have been added using XFBML. If you’re not using social plugins on the page, setting xfbml to false will improve page load times. You can find out more about this by looking at Social Plugins.

Triggering Code when the SDK loads

The function assigned to window.fbAsyncInit is run as soon as the SDK has completed loading. 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. Any kind of JavaScript can be used here, but any SDK functions must be called afterFB.init.


To improve performance, the JavaScript SDK is loaded minified. You can also load a debug version of the JavaScript SDK that includes more logging and stricter argument checking as well as being non-minified. To do so, change the js.src value in your loading code to this:

js.src = "//connect.facebook.net/en_US/sdk/debug.js";

More Initialization Options

The reference doc for the FB.init function provides a full list of available initialization options.

Using the SDK to add Social Plugins

Now that you’ve got the SDK setup, we can use it to perform a few common tasks. Social Plugins such as the Like Button and Comments Plugin can be inserted into HTML pages using the JavaScript SDK.

Let’s try adding a Like button, just copy and paste the line of code below anywhere inside the <body> of your page:


Reload your page, and you should see a Like button on it.

Using the SDK to trigger a Share dialog

The Share Dialog allows someone using a page to post a link to their timeline, or create an Open Graph story. Dialogs displayed using the JavaScript SDK are automatically formatted for the context in which they are loaded – mobile web, or desktop web.

Here we’ll show you how the FB.ui() method of the SDK can be used to invoke a really basic Share dialog. Add this snippet after the FB.init() call in the basic setup code:

  method: 'share',
  href: 'https://developers.facebook.com/docs/'
}, function(response){});

Now when you reload your page, you’ll see a Share dialog appear over the top of the page. Let’s add a few extra parameters to the FB.ui call in order to make the Share dialog make a more complex call to publish an Open Graph action:

     method: 'share_open_graph',
     action_type: 'og.likes',
     action_properties: JSON.stringify({
    }, function(response){});

Now when you reload your page, you’ll see a Share dialog again, but this time with a preview of the Open Graph story. Once the dialog has been closed, either by posting the story or by cancelling, the response function will be triggered.

Read the FB.ui reference doc to see a full list of parameters that can be used, and the structure of the response object.

Using the SDK for Facebook Login

Facebook Login allows users to register or sign in to your app with their Facebook identity.

We have a full guide on how to use the JS SDK to implement Facebook Login. But for now, let’s just use some basic sample code, so you can see how it works. Insert the following after your original FB.init call:

FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    console.log('Logged in.');
  else {

Read the Login guide to learn exactly what is happening here, but when you reload your page you should be prompted with the Login dialog for you app, if you haven’t already granted it permission.

Using the SDK to call the Graph API

To read or write data to the Graph API, you’ll use the JS SDK’s FB.api() method. The version parameter in the FB.init call is used to determine which Graph API version is used.

We have another quickstart guide for the Graph API, however here we’ll show you how the FB.api() method can publish a story on your behalf.

First, we need to get publish_actions permission in order to make publishing API calls. So add a line after FB.init like this:

FB.login(function(){}, {scope: 'publish_actions'});

This will trigger a login dialog that’ll request the relevant permissions. Next, now that your app can, let’s make the API call to publish. Add the API code into the response function of the FB.login call you added above:

 FB.api('/me/feed', 'post', {message: 'Hello, world!'});
}, {scope: 'publish_actions'});

Now, when you reload your page, you’ll be asked for permissions (if you haven’t granted them already) and then a status message will be posted to your profile:

Congratulations, you’ve learned how to use the JavaScript to perform a number of common tasks. Dig deeper into the guides linked in each section to learn more about specific methods, or other parts of Facebook Platform.
[Fuente : https://developers.facebook.com/docs/facebook-login/login-flow-for-web/v2.3]

Facebook Login for the Web with the JavaScript SDK

Facebook apps can use one of several login flows, depending on the target device and the project. This guide takes you step-by-step through the login flow for web apps. The steps in this guide use Facebook’s JavaScript SDK, which is the recommended method to add Facebook Login to your website.

If for some reason you can’t use our JavaScript SDK you can also implement login without it. We’ve build a separate guide to follow if you need to implement login manually.


Later in this doc we will guide you through the login flow step-by-step and explain each step clearly – this will help you if you are trying to integrate Facebook Login into an existing login system, or just to integrate it with any server-side code you’re running. But before we do that, it’s worth showing how little code is required to implement login in a web application using the JavaScript SDK.

You will need a Facebook App ID before you start using the SDK, which you can create and retrieve on the App Dashboard. You’ll also need somewhere to host HTML files. If you don’t have hosting, you can get set up quickly with Parse.

This code will load and initialize the JavaScript SDK in your HTML page. Use your app ID where indicated.

<!DOCTYPE html>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    } else {
      // The person is not logged into Facebook, so we're not sure if
      // they are logged into this app or not.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into Facebook.';

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {

  window.fbAsyncInit = function() {
    appId      : '{your-app-id}',
    cookie     : true,  // enable cookies to allow the server to access 
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.2' // use version 2.2

  // Now that we've initialized the JavaScript SDK, we call 
  // FB.getLoginStatus().  This function gets the state of the
  // person visiting this page and can return one of three states to
  // the callback you provide.  They can be:
  // 1. Logged into your app ('connected')
  // 2. Logged into Facebook, but not your app ('not_authorized')
  // 3. Not logged into Facebook and can't tell if they are logged into
  //    your app or not.
  // These three cases are handled in the callback function.

  FB.getLoginStatus(function(response) {


  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.
  function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';

  Below we include the Login Button social plugin. This button uses
  the JavaScript SDK to present a graphical Login button that triggers
  the FB.login() function when clicked.

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">

<div id="status">


Now you can test your app by going to the URL where you uploaded this HTML. Open your JavaScript console, and you’ll see the testAPI() function display a message with your name in the console log.

Congratulations, at this stage you’ve actually built a really basic page with Facebook Login. You can use this as the starting point for your own app, but it will be useful to read on and understand what is happening in the code above.