Tracking Social Engagement with Google Analytics

Google Analytics has recently introduced Social Interaction Tracking, a way to record and measure user interactions with social media buttons.  While it has been possible to track social interactions using Events, there is now a dedicated section that makes analysing Social actions even easier.  This post shows you how to set up social media tracking for Facebook and Twitter and gives you all you need to go on and set up social interaction tracking on your website.

Setting up the latest Google Analytics tracking code

The latest version of Google Analytics has built-in support for tracking +1 button interactions but Facebook and Twitter (and others) need a bit of JavaScript adding to a page to store data.

First, make sure you are using the latest version of the tracking code.  Google Analytics has provided an asynchronous tracking code for a while now so you will more than likely be using it. If you're unsure what that means, in a nutshell it loads the tracking code without stopping the rest of the page downloading (helping to speed up page load) and has a queue of things that should be tracked.  We will use that queue to add social tracking to our page.

 var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'your_code']);
_gaq.push(['_trackPageview']);
(function() {
    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
})();

From the code above you can see that the page view is recorded by this line:

_gaq.push(['_trackPageview']);

This is the queue that Google Analytics uses to decide what data to send to your analytics account.  To track social actions we will need to change _trackPageview to _trackSocial and offer some extra details, most importantly the social network and action taken.

The code you will need looks like this:

_gaq.push(['_trackSocial', network, action, optional-target, optional-path]);

Tracking Facebook Interactions

Facebook offers a range of social plugins to use on your website and within those plugins there are a range of events that we can hook into and track.

I'll mainly focus on the like and send buttons, but you can also track comments, logins, prompts, status changes and more.

You may need to change your implementation of the plugins slightly, especially if you have used the stock code generated by the examples on the developer pages of Facebook.  Don't worry, I actually think that my method of adding elements is easier as you will only need to load the Facebook script once and can build all XFBML elements in one go.

Using the like button as our example, you first need to make sure that the fb namespace is in your html tag:

xmlns:fb="http://www.facebook.com/2008/fbml">

You also need to make sure that you have an empty element that the Facebook script adds to:

<div id="fb-root"></div>

Then, simply add the like button to your page (this is typically how I choose to implement the like button, there are other options that you may want to include):

<fb:like href="" send="true" layout="button_count" width="150" show_faces="false"></fb:like>

If you view your page now, you won't see much as we havent implemented the JavaScript needed to render the like button.  Similarly to the Google Analytics implementation, I prefer to use the asynchronous method of loading the Facebook JavaScript SDK (note that this normally needs to be included underneath the fb-root div in your code):

(function() {
    var e = document.createElement('script');
    e.async = true;
    e.src = (document.location.protocol == 'file:' ? 'http:' : document.location.protocol) +              '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
}());

When loaded, this will look for a function on the overall window object called fbAsyncInit and we use this callback to initialise the XFBML elements (such as the like button) and to set up our social tracking.  I've chosen to track when users like, unlike and send a message:

window.fbAsyncInit = function() {
    FB.init({xfbml: true});
    FB.Event.subscribe('edge.create', function(targetUrl){
        _gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]);
    });
    FB.Event.subscribe('edge.remove', function(targetUrl){
        _gaq.push(['_trackSocial', 'facebook', 'unlike', targetUrl]);
    });
    FB.Event.subscribe('message.send', function(targetUrl) {
        _gaq.push(['_trackSocial', 'facebook', 'send', targetUrl]);
    });
};

That's it, if you open your page you should now have a like button, a send button, a tracked page view and tracking set up on the like and send buttons.

Twitter

Setting up tracking for twitter is very similar, with the only major difference being the way your JavaScript callback needs to  inspect an event for the targetUrl.  For this example I'm going to use the tweet button.

First, include the relevent HTML elements:

<a href="http://twitter.com/share" class="twitter-share-button" data-text="Tracking Social Interactions with Google Analytics" data-count="horizontal" data-via="anatomic"  data-related="anatomic:Website designer and developer">Tweet</a>

Here you can change the data-text to whatever you want (if it isn't included then Twitter will default to the page's title) and the data-via and data related can also be changed to the accounts of your choice.

Next, we set up the JavaScript that will render the Tweet button and give us the Twitter events:


Finally, we hook into the tweet event using the following JavaScript:

twttr.events.bind('tweet', function(event) {
    if (event) {
        var targetUrl;
        if (event.target && event.target.nodeName == 'IFRAME') {
            targetUrl = extractParamFromUri(event.target.src, 'url');
        }
        _gaq.push(['_trackSocial', 'twitter', 'tweet', targetUrl]);
    }
});

There's just one final element to add, which is the little bit of code to extract the url from the tweet button, it's fairly simple and is shown below:

function extractParamFromUri(uri, paramName){
    if(!uri){
        return;
    }
    var uri = uri.split('#')[0]; //remove anchor
    var parts = uri.split('?'); //check for query params
    if(parts.length == 1){
        return; //no params
    }
    
    var query = decodeURI(parts[1]);
    
    //find the url param
    paramName += '=';
    var params = query.split('&');
    for(var i = 0, param; param = params[i]; ++i){
        if(param.indexOf(paramName) === 0){
            return unescape(param.split('=')[1]);
        }
    }
}

As with Facebook, there are more events that you might want to hook into and you can see the full list at http://dev.twitter.com/pages/intents-events

The Google Analytics view

Once you have set the tracking up you'll start to see data flowing into your analytics account.  You'll need to be using the 'new version' option in google Analytics where you'll see the social option under the visitors tab.

From here you can see the percentage of your users that are socially engaged, the actions they take and the pages that they are active on.

A Quick Demo

To keep this post to a reasonable length I've not gone into any great detail about other elements that you can track.  With a bit of digging you can find them for yourself but for those in need of a quick fix I've put together a quick demo page that should have everything you need to get social tracking set up for the key plugins from Facebook and Twitter.

The demo includes Facebook like & send buttons, Facebook Comments, Twitter's Tweet button and the Twitter follow button.  Check it out!

If this post has been useful to you please share it!