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:

Supported Browsers

The Facebook SDK for JavaScript supports the latest two versions of the most popular browsers: Chrome, Firefox, Edge, Safari (including iOS), and Internet Explorer (version 11 only).

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