February 2013

Volume 28 Number 02

Cutting Edge - Essential Facebook Programming: The JavaScript SDK

By Dino Esposito | February 2013

Dino EspositoI’ll be honest: I don’t know exactly what a social strategy might look like and I have no more than a faint idea about the tricks that social experts can play to make your content more popular. Likewise, I never paid much attention to search engine optimization (SEO) in Web sites, but I do believe that social optimization is today much more relevant and rewarding than SEO ever was.

In the past two installments of this column, I discussed how to authenticate users of a Web or Windows application using Facebook and how to post to the social network on behalf of a consenting user. (Those two columns can be found at msdn.microsoft.com/magazine/jj863128 and msdn.microsoft.com/magazine/jj883950.)

As far as Facebook is concerned, there’s a lot more you can do to add a “social layer” to a Web site. A social layer results from the combination of three main ingredients: identity, community and interaction. In those previous columns, I addressed identity and a bit of interaction. Here, I’m going to explore the principal tools you can leverage to add a true social layer onto your existing Web site. According to Facebook, these tools are collectively known as social plug-ins. A social plug-in is a powerful mix of HTML markup, CSS and JavaScript code. It’s your responsibility as a Web developer to fuse these elements into the UX.

The Ubiquitous Like Button

The primary purpose of social plug-ins is to create a bridge between the content of the Web site visited by a user and the user’s Facebook page. By hosting one or more social plug-ins, the Web site enables users to share specific content with friends. The most immediate way for a Web site to let users share content via Facebook is the Like button.

By simply clicking the Like button, a user can let friends know that she likes something at a given URL. Hosting the Like button on a page couldn’t be simpler; fusing the button to the existing UI may require a few extra steps.

There are a few different ways to embed a Like button. The simplest and most direct way is using an iframe element:

<iframe src="https://www.facebook.com/plugins/like.php?href=your-site"
  scrolling="no" frameborder="0"
  style="border:solid 1px #000; width:450px; height:80px"></iframe>

The href query string parameter refers to the URL you want to like. The URL must be expressed in a fully qualified manner, something like https://www.contoso.com/cool.

Most of the markup is aimed at styling the iframe. Usually, you don’t want the iframe to scroll or be framed. You also want it to take up an appropriate area. The preceding markup produces the output in Figure 1.

The Standard Interface of the Like Button
Figure 1 The Standard Interface of the Like Button

If the height of the iframe is too small (less than 25 pixels or so), you lose the panel containing the button to post an additional comment. If you’re using the Like button within a horizontal menu bar, then the height is a critical issue. Otherwise, giving users a chance to also post their own comment augments the penetration of the feature.

There are several parameters you can leverage to customize the look, feel and functionality of the button. Figure 2 lists the options available. All will be assigned through an additional query string parameter.

Figure 2 Customizing Look, Feel and Functionality

Parameter Description
action Indicates the text of the button and the subsequent action to be taken. It can be Like or Recommend. Default is Like.
colorscheme Styles the button differently. It can be light or dark. Default is light.
font Sets the desired font for the plug-in. Possible options include Arial, Tahoma, Trebuchet MS and a few others.
layout Changes the layout of the button. Possible values are standard (as in Figure 1), button_count and box_count (as in Figure 3).
locale Indicates the language of the UI. It must be a string in the format xx_XX. Note the use of the underscore to separate the two parts of a culture name.
show_faces Boolean flag to indicate whether you want the picture of the user rendered once a user has liked the content.
width Indicates the width of the plug-in. The minimum width also depends on the layout used.

While Figure 1 shows the standard layout, Figure 3 shows the button_count and box_count layouts.

Additional Layout Formats (Button Count and Box Count) for the Like Butto
Figure 3 Additional Layout Formats (Button Count and Box Count) for the Like Button

Another parameter you should look into is the ref parameter. It helps you track use of the Like button in your Web site. By giving each Like button (even in different pages of the site) a different ref value—a plain alphanumeric string—you can easily track referrers in the server log that can be traced back to that specific Like button. In particular, for any click back from Facebook to your site, you’ll receive a referrer URL with two extra parameters. The fb_ref query string parameter is just your original ref string; the fb_source query string parameter is a string that gives you information about the context from within Facebook where the click originated. 

Localizing the Like Button

Even though the Like button can be considered universal, there still might be situations in which you want to translate the Like plug-in to a given language. As shown in Figure 2, all you need to do is add the locale parameter to the query string and set it to a custom string that indicates the desired language and culture.

To make things a bit trickier, you can’t express culture using the canonical xx-XX format where xx indicates the language and XX the culture. In the Microsoft .NET Framework, you get this string from the following expression:

var name = Thread.CurrentThread.CurrentUICulture.Name;

For this string to be usable with Facebook, you need to replace the dash with an underscore. Also note that the sole language token isn’t sufficient in itself and the whole locale setting will be ignored. This point leads me to another interesting consideration: What’s the default behavior of the Like button as far as the language is concerned?

Facebook, as well as Twitter, defaults to the language the user has chosen as the primary language in her profile. If the user isn’t currently logged in, then the UI is based on the language settings detected on the browser.

Introducing the JavaScript SDK

In general, you can configure Facebook’s plug-ins in a few different ways: using a plain URL from a custom hyperlink; using an iframe (as shown in this article); using HTML5 markup; and using the eXtended Facebook Markup Language (XFBML). HTML5 and XFBML are equivalent in many ways; HTML5 is just a more-­recent syntax supported for completeness. Both HTML5 and XFBML require the use of the Facebook JavaScript SDK.

Most sophisticated social plug-ins are only available through HTML5 and XFBML markup. This is the case for the Send button for sending content directly to friends and the Comments box to see the comments on a given post. Other plug-ins such as Like, the Like box and the Activity feed (the small list of notifications from all friends you usually have on the top-right corner of your page) also can be quickly configured and embedded via an iframe.

Plug-ins not implemented through iframes or direct URLs require the use of the Facebook JavaScript SDK. As you can imagine, the SDK is a client front-end for a number of Facebook endpoints for you to perform tasks such as authentication, posting and retrieving comments, likes, and other actions.

In order to use the JavaScript SDK, even before you download it, you must have an app ID. I thoroughly discussed this point in previous columns, but in a nutshell, for any interaction with the Facebook site that goes beyond basic operations such as Like, you need to register an app and get a unique ID. The app plays the role of the connector between your client (for example, a Web site) and the Facebook back end. The Facebook App Dashboard for registering an app is available at bit.ly/mly4xs.

The second step consists of adding some code to your Web pages that downloads the SDK. The URL to invoke is: /con­nect.facebook.net/xx_XX/all.js.

The xx_XX in the URL is a placeholder for the desired locale. An option is linking this URL from within a static script tag. Because the size of the file is far more than 180KB, it might not be a good idea to download it synchronously through a static script tag. The file gets cached soon and most of the successive requests for it will receive an HTTP 304 “not modified” status code; however, Facebook recommends you download the file asynchronously. This is a pattern common to all script blocks required for social interactions—for example, it works the same for Twitter plug-ins. Here’s the code you need:

<script type="text/javascript">   
  (function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s);
    js.id = id;
    js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=xxx";
    fjs.parentNode.insertBefore(js, fjs);
  } (document, 'script', 'facebook-jssdk'));
</script>

The code is defined as a JavaScript immediate function and runs as soon as it’s found. Note that you place this code preferably right after the opening body tag and you should fill the appId parameter with your app ID. (Note that many developers advocate placing scripts at the bottom of the body section in order to prevent any blocking of the rendering of the page.)

At this point, you’re ready to use HTML5 and XFBML tags to integrate Facebook plug-ins in your pages. Let’s start with a look at the Login button.

The Login Button

The SDK contains a method on the root FB object through which you can programmatically trigger the login process. The simplest option consists of adding your own link or button and binding its click handler to the following code:

FB.login(function(response) {
  if (response.authResponse) {
    // Display some wait message 
    // ...
    FB.api('/me', function(response) {
      $("#username").html('Welcome, ' + response.name + '.');
    });
  } });

This code is far simpler than any other analogous code in the past two columns. In this way, authenticating users against Facebook is a breeze (see Figure 4).

Authenticating Users via JavaScript
Figure 4 Authenticating Users via JavaScript

The Login plug-in can make the login process even easier. In addition to linking the SDK, all you need is the following HTML5 markup (or analogous XFBML markup as demonstrated on the Facebook site):

<div class="fb-login-button"
  data-show-faces="true"
  data-width="200" 
  data-max-rows="1"></div>

The data-* attributes let you configure the appearance and behavior of the button. The blue button in the page of Figure4 gives an idea of the standard look and feel. In particular, the data-show-faces attribute enables you to display the pictures of users (and some of their friends) that used your app to connect to Facebook. The data-max-rows attribute determines the number of rows (given the width of the plug-in) to be filled with faces.

It should also be noted that if data-show-faces is on and the user is already logged in, then no login button is shown. The user can’t log out from Facebook through your app. If data-show-faces is false, then the login button stays visible all the time and it doesn’t react if clicked.

As a Web developer, you should see the profound difference between using the JavaScript SDK or the Login plug-in and server-­side code and the Facebook C# SDK. If you work the client side, then you’re essentially targeting Facebook, and login is probably the necessary first step in order to do more specific work. Facebook is the goal here.

C# code is preferable if you’re using Facebook as just one way of authenticating users and still need to handle the authentication cookie of ASP.NET and the standard membership system. Facebook is the means here.

Coming Up

Provided that it’s not already so, authentication via social networks will become a must-have feature for all sites needing authentication. This means the C# SDK probably remains the most flexible approach. In this regard, the new social classes in ASP.NET MVC 4 are just icing on the cake. In terms of Web site development, I likewise see no reason for not populating page layouts with social buttons and plug-ins to tweet or post immediate content. Next time, I’ll be back with Facebook programming covering more advanced social plug-ins such as Comments and the Like box. Meanwhile, for more information on Facebook social plug-ins, you can have a look at bit.ly/fAU7Xe.


Dino Esposito is the author of “Architecting Mobile Solutions for the Enterprise” (Microsoft Press, 2012) and “Programming ASP.NET MVC 3” (Microsoft Press, 2011), and coauthor of “Microsoft .NET: Architecting Applications for the Enterprise” (Microsoft Press, 2008). Based in Italy, Esposito is a frequent speaker at industry events worldwide. Follow him on Twitter at twitter.com/despos.

Thanks to the following technical experts for reviewing this article: Christopher Bennage and Scott Densmore