Social Interactions - Web Tracking (ga.js)

This document describes how to use Google Analytics to get interaction metrics on non-Google networks such as Facebook and Twitter. Use this document to set up Analytics for your social sharing buttons if you are a site owner, a content management plug-in developer, or if you are a social network operator wanting to provide automatic social interaction reporting for users of your sharing buttons.

Introduction

By default, Google Analytics provides integrated reporting for the +1 Button. This means if you have implemented ga.js and a +1 Button on the same page, all +1 social interactions will be automatically reported. For more information on +1 Analytics, including troubleshooting tips, see About Social Analytics in the Help Center.

To get social interaction Analytics and reporting for other networks like Facebook or Twitter, you need to integrate Google Analytics with each network button. With Social Plug-in Analytics, recorded interactions range from a Facebook "Like" to a Twitter "Tweet." While event tracking can track general content interactions as well, Social Analytics provides a consistent framework for recording social interactions. This in turn provides Google Analytics report users with a consistent set of reports to compare social network interactions across multiple networks.

To see a working example of how to integrate Analytics with Facebook and Twitter buttons check out the Social Analytics sample code.

Setting Up Social Analytics

To set up tracking for social interactions, you'll need to use the _trackSocial method, which sends social interaction data to Google Analytics. The method should be called once a user has completed a social interaction. Each social network uses a different mechanism to determine when the social interaction occurs and this typically requires integrating with the API for that network button.

Since specific details for integrating Social Analytics varies by social network, the rest of this guide provides general best practices on how to set up Social Plug-in Analytics for each of these networks. We recommend you check the developer documentation for each network to figure out the network specific implementation.

Here is a description of the _trackSocial method:

_gaq.push(['_trackSocial', network, socialAction, opt_target, opt_pagePath]);

where the parameters represent:

  • network

    Required. A string representing the social network being tracked (e.g. Facebook, Twitter, LinkedIn).

  • socialAction

    Required. A string representing the social action being tracked (e.g. Like, Share, Tweet).

  • opt_target

    Optional. A string representing the URL (or resource) which receives the action. For example, if a user clicks the Like button on a page on a site, the the opt_target might be set to the title of the page, or an ID used to identify the page in a content management system. In many cases, the page you Like is the same page you are on. So if this parameter is undefined, or omitted, the tracking code defaults to using document.location.href.

  • opt_pagePath

    Optional. A string representing the page by path (including parameters) from which the action occurred. For example, if you click a Like button on https://developers.google.com/analytics/devguides/, then opt_pagePath should be set to /analytics/devguides. Almost always, the path of the page is the source of the social action. So if this parameter is undefined or omitted, the tracking code defaults to using location.pathname plus location.search. You generally only need to set this if you are tracking virtual pageviews by modifying the optional page path parameter with the Google Analytics _trackPageview method.

Facebook Actions

According to the Facebook JavaScript SDK, the simplest way to set up a Like button on your page is to use the following code:

<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
<fb:like></fb:like>

Likes

To record Likes with Google Analytics, subscribe to Facebook's edge.create event and create a callback function to execute the Google Analytics tracking code.

FB.Event.subscribe('edge.create', function(targetUrl) {
  _gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]);
});

When a user Likes your page, the callback function is executed and receives the URL of the resource being liked. The resource is then passed as a value to the _trackSocial method so Google Analytics can report on the network, action and URL being liked.

Unlikes

The Facebook APIs also let you subscribe to other interesting events such as unlikes.

FB.Event.subscribe('edge.remove', function(targetUrl) {
  _gaq.push(['_trackSocial', 'facebook', 'unlike', targetUrl]);
});

Shares

You can also subscribe to shares.

FB.Event.subscribe('message.send', function(targetUrl) {
  _gaq.push(['_trackSocial', 'facebook', 'send', targetUrl]);
});

Twitter Tweets

According to the Tweet Button Documentation and Web Intents Javascript Events, in order to implement a twitter button on your page and detect user interactions, the following code should be used :

<a href="http://developers.google.com/analytics" class="twitter-share-button" data-lang="en">Tweet</a>
<script type="text/javascript" charset="utf-8">
  window.twttr = (function (d,s,id) {
    var t, js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;
    js.src="//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
    return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } });
  }(document, "script", "twitter-wjs"));
</script>

To track Tweet Button events with Google Analytics, you need to use Twitter's Web Intents Javascript Events and bind a callback function to the Intent Event. It is important to wrap event bindings in a callback function to ensure everything has loaded before binding events.

function trackTwitter(intent_event) {
  if (intent_event) {
    var opt_pagePath;
    if (intent_event.target && intent_event.target.nodeName == 'IFRAME') {
          opt_target = extractParamFromUri(intent_event.target.src, 'url');
    }
    _gaq.push(['_trackSocial', 'twitter', 'tweet', opt_pagePath]);
  }
}

//Wrap event bindings - Wait for async js to load
twttr.ready(function (twttr) {
  //event bindings
  twttr.events.bind('tweet', trackTwitter);
});

When a user Tweets, the callback function receives an object which can usually be used to get the URL of the resource being tweeted. Once the Twitter JavaScript code loads, it transforms the annotated tweet link into an iframe and the URL being tweeted gets encoded and appended as a query parameter to the URL of the iframe. The event object passed to our callback has a reference to this iframe and we can use that to get the URL of the resource being tweeted.

The callback function above makes sure the iframe reference is indeed an iframe and then tries to extract the resource being tweeted by looking at the url query parameter.

Here's an example function to extract a query parameter from a URI:

function extractParamFromUri(uri, paramName) {
  if (!uri) {
    return;
  }
  var regex = new RegExp('[\\?&#]' + paramName + '=([^&#]*)');
  var params = regex.exec(uri);
  if (params != null) {
    return unescape(params[1]);
  }
  return;
}

The parameter is returned if it is located in the query string. If no parameter is located, then the function returns undefined, which is passed to the _trackSocial method, resulting in the default behavior of the method.

Best Practices for Integration

Many sites add social buttons by using content management plugins. If you are the author of such plugins, we highly recommend you integrate Social Plug-in Analytics to automatically record these interactions. Similarly, if you are a developer at a Social Network, you can also make it much easier for users to track your social network interactions in Google Analytics by integrating with Social Analytics.

To help you out, this section describes best practices for integrating Social Plug-in Analytics so that your product or CMS automatically tracks social interactions. If you want to see a working example of all these best practices, check out the Social Plug-in Analytics sample code.

Instantiating and Using the _gaq Queue

The latest version of the Google Analytics tracking code supports being loaded both synchronously and asynchronously. To let developers call methods which haven't loaded yet, Google Analytics provides a command queue _gaq, onto which tracking methods can be pushed _gaq.push();.

Once the tracking code is loaded, all the commands on the queue get executed. When integrating the Google Analytics JavaScript tracking code with your plug-in or product, you should always ensure this command queue is instantiated and that your integration pushes the _trackSocial command to this array.

var _gaq = _gaq || [];

This provides reasonable assurance that the method will get called regardless of whether the receiving website page uses the traditional or asynchronous tracking code snippet.

User Configurations

If you are developing a plug-in that integrates Social Plug-in Analytics, you should consider supplying the following options that allow users to set when they use your plugin:

Setting the optional page path parameter — The final parameter to the _trackSocial method is to override the current URL from which a social interaction occurred. The end goal is to have the same URLs being reported between page tracking and Social Plug-in Analytics. Since some users might override the default page URL being tracked with page view tracking, they also need a way to override the URL in Social Plug-in Analytics in order to achieve consistent reporting.

Here's an example of how you can let users set these options, as well as how your code needs to respond to them.

// Create a function for a user to call to pass in the options.
function trackFacebook(opt_pagePath) {
  try {
    if (FB && FB.Event && FB.Event.subscribe) {
      FB.Event.subscribe('edge.create', function(targetUrl) {
        _gaq.push(['_trackSocial', 'facebook', 'like',
            opt_target, opt_pagePath]);
      });
    }
  } catch(e) {}
}

In the example above, if the trackFacebook function is called with the opt_pagePath parameter set, the default page path value will be over-written with the supply path from the parameter. Otherwise, the value for that parameter will be set to undefined. and the Google Analytics tracking code will use the default value for the undefined parameter.

Note: In this example, a couple of checks have also been added to ensure no script errors occur if the Facebook API hasn't loaded. As a responsible developer, you should make sure you handle errors appropriately.

Multiple Trackers

Some Google Analytics users name their tracking object to distinguish multiple trackers on the same page. While we don't encourage the use of multiple trackers on the same website page, you might consider handling multiple trackers.

Below is an example of how to iterate through and call the _trackSocial method for each tracker object. It uses the _getTrackers method which returns an array of all tracker objects on the page.

In this example, when the Facebook event is triggered, the _trackSocial method for each tracker object is pushed onto the Google Analytics command queue _gaq.

getSocialActionTrackers = function(network, socialAction, opt_target, opt_pagePath) {
  return function() {
    var trackers = _gat._getTrackers();
    for (var i = 0, tracker; tracker = trackers[i]; i++) {
      tracker._trackSocial(network, socialAction, opt_target, opt_pagePath);
    }
  };
}

function trackFacebook(opt_pagePath) {
  try {
    if (FB && FB.Event && FB.Event.subscribe) {
      FB.Event.subscribe('edge.create', function(targetUrl) {
        _gaq.push(_ga.getSocialActionTrackers_('facebook', 'like',
            opt_target, opt_pagePath));
      });
    }
  } catch(e) {}
}