JavaScript SDK - Examples

Read our quickstart guide to learn how to load and initialize the Facebook SDK for JavaScript and our advanced setup guide to customize your implementation. Next try our examples for using the SDK:

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:


FB.ui({
  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:


FB.ui({
  method: 'share_open_graph',
  action_type: 'og.likes',
  action_properties: JSON.stringify({
    object:'https://developers.facebook.com/docs/javascript/examples',
  })
}, function(response){
  // Debug response (optional)
  console.log(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.

Read `FB.ui` Reference Documentation

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.login(function(response) {
    if (response.authResponse) {
     console.log('Welcome!  Fetching your information.... ');
     FB.api('/me', function(response) {
       console.log('Good to see you, ' + response.name + '.');
     });
    } else {
     console.log('User cancelled login or did not fully authorize.');
    }
});
    

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.

Learn more about Facebook Login