Tracking user interactions with Facebook and Twitter buttons with Google Analytics

Sunday January 20, 2013 ()

In this blog we will demonstrate how to track user interaction with Facebook like button and Twitter tweet button in a webpage using Google Analytics. We will use the asynchronous versions of Facebook and Twitter JavaScript SDK. We will also show how to track other user actions in your page like opening a lightbox.

To start, make sure you have Google Analytics tracker code in your HTML page. If you dont have them yet, sign-up for an Analytics account here http://www.google.com/analytics/ to get a tracker code (see code below), and add them to your page. You then have to create a custom analytics report and include the "Social" metrics for you to be able to see what is happening.

<!-- Google Analytics tracking code -->
<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'your-account-number']);
    _gaq.push(['_setDomainName', 'your-domain']);
    _gaq.push(['_setAllowHash', 'false']);
    _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);
    })();
</script>

Analytics provides a global queue variable _gaq (line 3 above), into which commands can be added and get executed. It is into this queue that the _trackSocial command which is provided for tracking event generated by user interaction to social objects in the page, is added. Below is the general format of the _trackSocial command as added to the queue _gaq.

_gaq.push(['_trackSocial', network, socialAction, targetPage, pageParameters]);

targetPage and pageParameters are optional parameters. When not provided targetPage defaults to current page (document.location.href) and pageParameters defaults to location.pathname

The common practice, which is also recommended by Analytics, is to have only one tracking code in the page. What we describe here works for pages with only one Google Analytics tracking code.

Tracking Facebook events

The Facebook Javascript SDK asynchrnous code look like below. Replace you-app-id with your own Facebook AppId. Line 9 below is the tracker code we inserted.

<div id="fb-root">
<script> window.fbAsyncInit = function() { FB.init({appId: 'you-app-id', status: true, cookie: true, xfbml: true}); trackFacebook(); }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1 &appId=your-app-id"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script>

Facebook events tracking is accomplish by providing callbacks when a specific Facebook event occurs. This is done in our trackFacebook() function. In the example below we used like, unlike and send message events. In these events, the parameter to the subscribe callback is the page where the event happened, it is the page where we are in. See the event subscribe documentation for more of the events you can monitor.

function trackFacebook() {   
    try { 
        if (FB && FB.Event && FB.Event.subscribe) {  

            FB.Event.subscribe('edge.create', function(response) {
                _gaq.push(['_trackSocial', 'facebook', 'like',response]);
            });   
            FB.Event.subscribe('edge.remove', function(response) {
                _gaq.push(['_trackSocial', 'facebook', 'unlike',response]);
            });   
                
            FB.Event.subscribe('message.send', function(response) {
                _gaq.push(['_trackSocial', 'facebook', 'send',response]);
            });   
        }
    } catch (e){}
}

Tracking Twitter events

In order to track user interaction, it is recommended to use the Twitter Web intent Javascript SDK. Our tracking code is inserted beginning at line 13.

<script type="text/javascript" charset="utf-8">
    // Web intent code
    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")); 

    // Social tracker
    twttr.ready(function(twttr) {
        twttr.events.bind('click', trackTwitter);
        twttr.events.bind('tweet', trackTwitter);
    });

</script>

Binding to Twitter events is made after the Twitter's asynchronous code loads completely, this is the block starting in line 13 above. Below is the trackTwitter() bound to the intent event.

function trackTwitter (event) {     
    if (event) {
        var action = event.type + ((event.type == 'click') ?
            '-' + event.region : '');
        
        _gaq.push(['_trackSocial', 'twitter', action]);  
    }
}

Twitter's click event is triggered when the user clicks anywhere in the tweet button. tweet event is generated when the tweet is completed.

Other events

It is also possible to track other events in your page, like opening an image lightbox. All that is needed is to handle the onclick event of a hyperlink.

_gaq.push(['_trackEvent', category, action, label, value, noninteraction]);

The last three parameters are optional. Parameter label is a string, value is of type integer and noninteraction is a boolean parameter. These parameters are explained in detail by Google in their events tracking guide.

Here is an example.

<a href="/images/mainstorm.jpg" rel="lightbox"
    onClick=
      "_gaq.push(['_trackEvent', 'images', 'click', 'Storm image']);">
Basin Image
</a>

The complete JavaScript code described in this demonstration

// Initialize the queue
var _gaq = _gaq || [];
 
function trackTwitter (event) {     
    if (event) {
        var action = event.type + ((event.type == 'click') ?
            '-' + event.region : '');
        
        _gaq.push(['_trackSocial', 'twitter', action]);  
    }
}

function trackFacebook() {   
    try { 
        if (FB && FB.Event && FB.Event.subscribe) {  

            FB.Event.subscribe('edge.create', function(response) {
                _gaq.push(['_trackSocial', 'facebook', 'like',response]);
            });   
            FB.Event.subscribe('edge.remove', function(response) {
                _gaq.push(['_trackSocial', 'facebook', 'unlike',response]);
            });   
                
            FB.Event.subscribe('message.send', function(response) {
                _gaq.push(['_trackSocial', 'facebook', 'send',response]);
            });   
        }
    } catch (e){}
}

function trackOtherEvents(category,label,value) {
    _gaq.push(['_trackEvent', category, label, value]);
}

You may want to save this as a JavaScript file and include this file in your page as the value of the src attribute of a <script /> tag.

That's it Good Luck.


2,308

Comments (Tracking user interactions with Facebook and Twitter buttons with Google Analytics)





Share icon