Initialization

FB.init ( opts )

Initialize the library:

<div id="fb-root"></div>
<script src="http://mu.daaku.org/m.js"></script>
<script>
  FB.init({ apiKey: 'YOUR API KEY' });
</script>

The best place to put this code is right before the closing </body> tag.

Options:

Property Type Description Argument Default
apiKey String Your application API key. Required  
cookie Boolean true to enable cookie support. Optional false
logging Boolean false to disable logging. Optional true
session Object Use specified session object. Optional null
status Boolean true to fetch fresh status. Optional false

Note: FB.publish() and FB.share() can be used without registering an application or calling this method. If you are using an API key, all methods must be called after this method.

Parameters:
opts Object options

Authentication & Authorization

FB.loginStatus ( cb , force )

Find out the current status from the server, and get a session if the user is connected.

The User's Status or the question of "who is the current user" is the first thing you will typically start with. For the answer, we ask facebook.com. Facebook will answer this question in one of two ways:

  1. Someone you don't know.
  2. Someone you know and have interacted with. Here's a session for them.

Here's how you find out:

FB.loginStatus(function(response) {
  if (response.session) {
    // logged in and connected user, someone you know
  } else {
    // no user session available, someone you dont know
  }
});

The example above will result in the callback being invoked once on load based on the session from www.facebook.com. For more advanced use, you may with to monitor for various events.

Events

  • auth.login
  • auth.logout
  • auth.sessionChange
  • auth.statusChange

The FB.Event.subscribe() and FB.Event.unsubscribe() functions are used to subscribe to these events. For example:

FB.Event.subscribe('auth.login', function(response) {
  // do something with response
});

The response object returned to all these events is the same as the response from FB.loginStatus(), FB.login() or FB.logout().

Parameters:
cb Function the callback function
force Boolean force reloading the login status (default false)
FB.login ( cb , perms )

Login/Authorize/Permissions.

Once you have determined the user's status, you may need to prompt the user to login. It is best to delay this action to reduce user friction when they first arrive at your site. You can then prompt and show them the "Connect with Facebook" button bound to an event handler which does the following:

FB.login(function(response) {
  if (response.session) {
    // user successfully logged in
  } else {
    // user cancelled login
  }
});

You should only call this on a user event as it opens a popup. Most browsers block popups, unless they were initiated from a user event, such as a click on a button or a link.

Depending on your application's needs, you may need additional permissions from the user. A large number of calls do not require any additional permissions, so you should first make sure you need a permission. This is a good idea because this step potentially adds friction to the user's process. Another point to remember is that this call can be made even after the user has first connected. So you may want to delay asking for permissions until as late as possible:

FB.login(function(response) {
  if (response.session) {
    if (response.perms) {
      // user is logged in and granted some permissions.
      // perms is a comma separated list of granted permissions
    } else {
      // user is logged in, but did not grant any permissions
    }
  } else {
    // user is not logged in
  }
}, 'read_stream,publish_stream,offline_access');
Parameters:
cb Function the callback function
perms String (optional) comma separated list of permissions
FB.logout ( cb )

Logout the user in the background.

Just like logging in is tied to facebook.com, so is logging out. The status shared between your site and Facebook, and logging out affects both sites. This is a simple call:

FB.logout(function(response) {
  // user is now logged out
});
Parameters:
cb Function the callback function
FB.getSession () : Object
Accessor for the current Session.
Returns:
  Object the current Session if available, null otherwise

Guide

Click here for a detailed guide explaining Authentication and Authorization. The guide provide information about the response object returned by FB.loginStatus(), FB.login() and FB.logout(), including the various status, the session object and sample code for various scenarios.

Events

Events provide a generic way for you to get notified and perform some action. For example, when the user sign's in or out. The current set of events includes:

  • auth.login
  • auth.logout
  • auth.sessionChange
  • auth.statusChange

FB.Event.subscribe ( name , cb )

Bind an event handler to a given event name.

For example, suppose you want to get notified whenever the session changes:

FB.Event.subscribe('auth.sessionChange', function(response) {
  // do something with response.session
});
Parameters:
name String name of the event
cb Function the handler function
FB.Event.unsubscribe ( name , cb )

Removes subscribers, inverse of FB.Event.subscribe().

Removing a subscriber is basically the same as adding one. You need to pass the same event name and function to unsubscribe that you passed into subscribe. If we use a similar example to FB.Event.subscribe, we get:

var onSessionChange = function(response) {
  // do something with response.session
};
FB.Event.subscribe('auth.sessionChange', onSessionChange);

// sometime later in your code you dont want to get notified anymore
FB.Event.unsubscribe('auth.sessionChange', onSessionChange);
Parameters:
name String name of the event
cb Function the handler function

API Calls

FB.api ( params , cb )

Once you have a session for the current user, you will want to access data about that user, such as getting their name & profile picture, friends lists or upcoming events they will be attending. In order to do this, you will be making signed API calls to Facebook using their session. Suppose we want to alert the current user's name:

FB.api(
  {
    method: 'fql.query',
    query: 'SELECT name FROM profile WHERE id=' + FB.getSession().uid
  },
  function(response) {
    alert(response[0].name);
  }
);

API Calls are listed here: http://wiki.developers.facebook.com/index.php/API

FQL is the preferred way of reading data from Facebook (write/update/delete queries are done via simpler URL parameters). FQL.multiQuery is also very crucial for good performance, as it allows efficiently collecting different types of data.

FQL is described here: http://wiki.developers.facebook.com/index.php/FQL

FQL Tables are listed here: http://wiki.developers.facebook.com/index.php/FQL_Tables

Parameters:
params Object the parameters for the query
cb Function the callback function to handle the response

Integration

FB.publish ( post , cb )

Publish a post to the stream.

This is the main, fully featured distribution mechanism for you to publish into the user's stream. It can be used, with or without an API key. With an API key you can control the Application Icon and get attribution. You must also do this if you wish to use the callback to get notified of the post_id and the message the user typed in the published post, or find out if the user did not publish (clicked on the skipped button).

Publishing is a powerful feature that allows you to submit rich media and provide a integrated experience with control over your stream post. You can guide the user by choosing the prompt, and/or a default message which they may customize. In addition, you may provide image, video, audio or flash based attachments with along with their metadata. You also get the ability to provide action links which show next to the "Like" and "Comment" actions. All this together provides you full control over your stream post. In addition, if you may also specify a target for the story, such as another user or a page.

A post may contain the following properties:

Property Type Description
message String This allows prepopulating the message.
attachment Array An attachment object.
action_links Array An array of action links.
actor_id String A actor profile/page id.
target_id String A target profile id.
user_message_prompt String Custom prompt message.

The post and all the parameters are optional, so use what is best for your specific case.

Example:

var post = {
  message: 'getting educated about Facebook Connect',
  attachment: {
    name: 'Mu Connect',
    caption: 'A micro Facebook Connect library.',
    description: (
      'Mu is 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://mu.daaku.org/'
  },
  action_links: [
    { text: 'Mu Console', href: 'http://mu.daaku.org/' },
    { text: 'GitHub Repo', href: 'http://github.com/nshah/mu' }
  ],
  user_prompt_message: 'Share your thoughts about Mu Connect'
};

FB.publish(
  post,
  function(published_post) {
    if (published_post) {
      alert(
        'The post was successfully published. ' +
        'Post ID: ' + published_post.post_id +
        '. Message: ' + published_post.message
      );
    } else {
      alert('The post was not published.');
    }
  }
);
Parameters:
post Object the post object
cb Function called with the result of the action
FB.share ( u , title )

Sharing is the light weight way of distributing your content. As opposed to the structured data explicitly given in the publish call, with share you simply provide the URL and optionally a title:

FB.share('http://mu.daaku.org/', 'Mu Connect');

Both arguments are optional, and just calling FB.share() will share the current page.

This call can be used without requiring the user to sign in.

Parameters:
u String the url (defaults to current URL)
title String a custom title
FB.addFriend ( id , cb )
Prompt the user to add the given id as a friend.
Parameters:
id String the id of the target user
cb Function called with the result of the action