My favorites | English | Sign in

Google Friend Connect APIs (Labs)

In-page Integration of GFC JS API

Google's Friend Connect service gives you an easy way to add social features to your site. Typically, this is done by copying and pasting a snippet of code to the HTML of your site. This code creates an <iframe> containing a social gadget, such as a sign-in gadget or a comment wall. The <iframe> approach makes getting up and running with Friend Connect fast and easy, but it keeps Friend Connect's social data locked inside of the <iframe> itself, meaning that you can't call Friend Connect's JavaScript functions directly from the source of your HTML page.

Thankfully, a new inline Friend Connect JavaScript library allows you to access the Friend Connect data without the use of <iframe>s, opening the door to deeper integrations between social data and your website. This article will walk you through the process of configuring a site to use the inline library, and demonstrate how to add social functionality to a blank HTML page.

You can view the complete sample here , and each section of this tutorial is available to edit in the code Playground if you want to follow along.

Contents

  1. Setting up a website to use the inline Friend Connect library
  2. Configuring the inline Friend Connect JavaScript library
  3. Working with Friend Connect data
    1. Fetching the site information
    2. Fetching information about the members of your site
    3. Adding controls for the current user
    4. Final source listing
  4. For more information

Setting up a website to use the inline Friend Connect library

To use the Friend Connect inline JavaScript library, you'll still need to set up your website in the same way that you would to register a normal Friend Connect site. Head to http://www.google.com/friendconnect/ and click "Set up a new site". You'll be asked to input some information about your website, and to upload two files to your web server. For assistance with these steps, please consult the Friend Connect help FAQ.

Once you have your site properly set up for Friend Connect, visit the Friend Connect panel and click the "For Programmers" link on the list of links underneath the name of the site you have just set up. The "For Programmers" page will give you a snippet of code to copy and paste into the HTML of any of the pages of your website. For reference, this will look something like the following:

  <!-- Load the Google AJAX API Loader -->
  <script type="text/javascript" src="http://www.google.com/jsapi"></script>

  <!-- Load the Google Friend Connect javascript library. -->
  <script type="text/javascript">
    google.load('friendconnect', '0.8');
  </script>

  <!-- Initialize the Google Friend Connect OpenSocial API. -->
  <script type="text/javascript">
  google.friendconnect.container.initOpenSocialApi({
    site: '####################',
    onload: function(securityToken) { /* your callback, which is passed a security token */ }
  });
  </script>

The <head> element of your website is a good place to paste this code.

Note that the ID number represented by #################### will actually be a unique number for each site, so you'll need to change this to your site's ID number if you want to copy and paste the code from this article. However, the "For Programmers" page in the Friend Connect admin site will have the correct values automatically inserted.

Configuring the inline Friend Connect JavaScript library

If you copied and pasted the code from the "For Programmers" page, your page will be automatically configured with the correct settings for your website. The pasted code snippet does the following:

  1. Adds the Google AJAX API Loader to your page.
  2. Calls google.load to load the Friend Connect API.
  3. Calls google.friendconnect.container.initOpenSocialApi to add the OpenSocial JavaScript APIs directly into your website.

Note that the Google AJAX API Loader isn't limited to just FriendConnect. You can use this tool to import a variety of Google and third party libraries to your site simply by adding additional google.load statements to this code.

Since any calls to retrieve social data before the OpenSocial APIs are loaded will result in JavaScript errors, configure your library to execute a callback once everything is loaded. Change the line that reads:

onload: function(securityToken) { /* your callback, which is passed a security token */ }

to

onload: function(securityToken) { initAllData(); }

Finally, initAllData doesn't exist in the JavaScript code of your website right now, so put the following somewhere in your <body> tag:

<script type="text/javascript">
  function initAllData() {
  
  };
</script>

Working with Friend Connect data

By now, you should have a page that looks something like the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>Your website's title</title>
    <!-- Load the Google AJAX API Loader -->
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>

    <!-- Load the Google Friend Connect javascript library. -->
    <script type="text/javascript">
      google.load('friendconnect', '0.8');
    </script>

    <!-- Initialize the Google Friend Connect OpenSocial API. -->
    <script type="text/javascript">
    google.friendconnect.container.initOpenSocialApi({
      site: '####################',
      onload: function(securityToken) { /* your callback, which is passed a security token */ }
    });
    </script>
  </head>
  <body>
    <script type="text/javascript">
      function initAllData() {

      };
    </script>
  </body>
</html>

At least make sure that the parts in bold are included in your site in the appropriate places. Congratulations, your site is now configured to use JavaScript to request data from Friend Connect users!

The following sections will demonstrate how to fetch different types of data from Friend Connect. Be sure to add the following samples to the JavaScript code block thatcontains the initAllData method. Additionally, we'll be adding some HTML elements to the page, but it's not so important where those elements get added, so just put them somewhere in the <body> tag.

Most of the concepts we'll be working with are based on the OpenSocial specification, so you may want to familiarize yourself with that API if you have trouble following along.

Fetching the site information

FriendConnect treats the website it is running on as the owner, in OpenSocial terms. Fetching the owner's data actually fetches information about the site itself.

This section will show you how to request information about the site. Your code will:

  1. Request the owner in the initAllData function.
  2. Specify a callback function named onData that will handle the server's response.
  3. Check the server's response for an error.
  4. Place the name of the owner into an HTML element.

Start by editing the initAllData() function to contain the following:

function initAllData() {
  var req = opensocial.newDataRequest();
  req.add(req.newFetchPersonRequest("OWNER"), "owner_data");
  req.send(onData);
};

Now add another method to the same script tag, called onData, which will be called once the data is fetched from the server:

function onData(data) {
  if (!data.get("owner_data").hadError()) {
    var owner_data = data.get("owner_data").getData();
    document.getElementById("site-name").innerHTML = owner_data.getDisplayName();
  }
};

Since the above snippet references an HTML tag with the id of site-name, put the following somewhere in the <body> of the document (outside of a <script> tag, of course!):

  <p>The name of this site is <strong><span id="site-name"></span></p>

If you run this sample now, you will see the name of the website that you entered in the Friend Connect setup page listed on your site.

Fetching information about the members of your site

Time to add some social data to this page! This section will show you how to display a list of Friend Connect users who have joined your website. You will modify the sample to fetch a list of the owner's friends. This is as easy as changing the initAllData function to the following (new lines in bold):

function initAllData() {
  var req = opensocial.newDataRequest();
  req.add(req.newFetchPersonRequest("OWNER"), "owner_data");
  var idspec = new opensocial.IdSpec({
      'userId' : 'OWNER',
      'groupId' : 'FRIENDS'
  });
  req.add(req.newFetchPeopleRequest(idspec), 'site_friends');
  req.send(onData);
};

Then, add the following code to the onData function:

function onData(data) {
  if (!data.get("owner_data").hadError()) {
    var owner_data = data.get("owner_data").getData();
    document.getElementById("site-name").innerHTML = owner_data.getDisplayName();
  }

  if (!data.get("site_friends").hadError()) {
    var site_friends = data.get("site_friends").getData();
    var list = document.getElementById("friends-list");
    list.innerHTML = "";
    site_friends.each(function(friend) {
      list.innerHTML += "<li>" + friend.getDisplayName() + "</li>";
    });
  }
};

You'll need a list element also, so add the following to your HTML:

  <p>The name of this site is <strong><span id="site-name"></span></p>
  <p>The members of this site are:</p>
  <ol id="friends-list"></ol>

By adding the code listed, you'll be able to fetch and iterate over a list of users who have joined your website. For each person, this code will print the user's name (although there are certainly other things you can display, such as thumbnail photos).

There are some limits to the code in this sample- for example, you'll only retrieve 20 or so names at a time with a normal request. For information about how to increase this number, or page through multiple sets of results, check the Requesting Data in OpenSocial article.

Adding controls for the current user

Anyone who visits your site will be unable to join unless you give them links to do so. Let's add some code to display a sign-in button for unauthenticated users, and a welcome message and some utility links for users who are already signed in. Once again, add the following to initAllData:

function initAllData() {
  var req = opensocial.newDataRequest();
  req.add(req.newFetchPersonRequest("OWNER"), "owner_data");
  req.add(req.newFetchPersonRequest("VIEWER"), "viewer_data");
  var idspec = new opensocial.IdSpec({
      'userId' : 'OWNER',
      'groupId' : 'FRIENDS'
  });
  req.add(req.newFetchPeopleRequest(idspec), 'site_friends');
  req.send(onData);
};

The viewer in this case represents the person currently interacting with your site in the browser. If this information is available, the person has logged in. If not, they are effectively anonymous to your site. We'll check for this case in the onData function:

function onData(data) {
  if (!data.get("owner_data").hadError()) {
    var owner_data = data.get("owner_data").getData();
    document.getElementById("site-name").innerHTML = owner_data.getDisplayName();
  }

  var viewer_info = document.getElementById("viewer-info");
  if (data.get("viewer_data").hadError()) {
    google.friendconnect.renderSignInButton({ 'id': 'gfc-button' });
    document.getElementById('gfc-button').style.display = 'block';
    viewer_info.innerHTML = '';
  } else {
    document.getElementById('gfc-button').style.display = 'none';
    var viewer = data.get("viewer_data").getData();
    viewer_info.innerHTML = "Hello, " + viewer.getDisplayName() + " " +
        "<a href='#' onclick='google.friendconnect.requestSettings()'>Settings</a> | " + 
        "<a href='#' onclick='google.friendconnect.requestInvite()'>Invite</a> | " +
        "<a href='#' onclick='google.friendconnect.requestSignOut()'>Sign out</a>";
  }
    
  if (!data.get("site_friends").hadError()) {
    var site_friends = data.get("site_friends").getData();
    var list = document.getElementById("friends-list");
    list.innerHTML = "";
    site_friends.each(function(friend) {
      list.innerHTML += "<li>" + friend.getDisplayName() + "</li>";
    });
  }
};

As usual, we'll also need another HTML element:

  <p>The name of this site is <strong><span id="site-name"></span></p>
  <p id="viewer-info"></p>
  <p>The members of this site are:</p>
  <ol id="friends-list"></ol>

That's it! You've just converted an empty HTML page to a dynamic website that allows users to securely log in with their accounts from several different web services, all through the use of a few lines of JavaScript and HTML. In addition, your site retrieves social information from the Friend Connect servers and renders it as a log of users who have joined your site.

Final source listing

For your reference, here's what that empty HTML file from the start of this article should now look like:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>Your website's title</title>
    <!-- Load the Google AJAX API Loader -->
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>

    <!-- Load the Google Friend Connect javascript library. -->
    <script type="text/javascript">
      google.load('friendconnect', '0.8');
    </script>

    <!-- Initialize the Google Friend Connect OpenSocial API. -->
    <script type="text/javascript">
    google.friendconnect.container.initOpenSocialApi({
      site: '####################',
      onload: function(securityToken) { initAllData(); }
    });
    </script>
  </head>
  <body>
    <script type="text/javascript">
      function initAllData() {
        var req = opensocial.newDataRequest();
        req.add(req.newFetchPersonRequest("OWNER"), "owner_data");
        req.add(req.newFetchPersonRequest("VIEWER"), "viewer_data");
        var idspec = new opensocial.IdSpec({
            'userId' : 'OWNER',
            'groupId' : 'FRIENDS'
        });
        req.add(req.newFetchPeopleRequest(idspec), 'site_friends');
        req.send(onData);
      };
      
      function onData(data) {
        if (!data.get("owner_data").hadError()) {
          var owner_data = data.get("owner_data").getData();
          document.getElementById("site-name").innerHTML = owner_data.getDisplayName();
        }

        var viewer_info = document.getElementById("viewer-info");
        if (data.get("viewer_data").hadError()) {
          viewer_info.innerHTML = "<a href='#' onclick='google.friendconnect.requestSignIn()'>Sign in</a>";
        } else {
          var viewer = data.get("viewer_data").getData();
          viewer_info.innerHTML = "Hello, " + viewer.getDisplayName() + " " +
              "<a href='#' onclick='google.friendconnect.requestSettings()'>Settings</a> | " + 
              "<a href='#' onclick='google.friendconnect.requestInvite()'>Invite</a> | " +
              "<a href='#' onclick='google.friendconnect.requestSignOut()'>Sign out</a>";
        }

        if (!data.get("site_friends").hadError()) {
          var site_friends = data.get("site_friends").getData();
          var list = document.getElementById("friends-list");
          list.innerHTML = "";
          site_friends.each(function(friend) {
            list.innerHTML += "<li>" + friend.getDisplayName() + "</li>";
          });
        }
      };
    </script>
    <p>The name of this site is <strong><span id="site-name"></span></p>
    <p><div id="gfc-button"></div></p>
    <p id="viewer-info"></p>
    <p>The members of this site are:</p>
    <ol id="friends-list"></ol>
  </body>
</html>

For more information

With this sample under your belt, you should start thinking about more sophisticated uses of this technology, and ways that you can integrate Friend Connect with existing functionality on your site. A great place to see a more sophisticated example is the Friend Connect integration example site. This site builds upon the inline samples listed here, but uses Activities to allow users to interact with the website by choosing their favorite color. Just load the page and select "view source" in your browser to see the code that makes this possible.

Since this technology is built on OpenSocial, many of the OpenSocial JavaScript calls will work with Friend Connect. Check the OpenSocial JavaScript documentation for more functions that you can use to interact with the members of your website. Remember, a social site is a happy one!