Track events for Google Analytics and Piwik

After my post of yesterday, I've worked for creating a script to integrate Google Analytics (new version with analytics.js) and Piwik (Piwik is the leading open-source analytics platform similar to Google Analytics. You can download it from its site or directly in your IIS with WebMatrix).

With this code you have only one function to call in every part of your page. Automatically the function detects download, email, phone number, external links and tracks them. You can insert in an anchor a code like:

<a href="http://www.puresourcecode.com/" 
   onclick="TrackEvent('Link to my site', 'PSC', 
            'Click from the user', 'Url or something else');">
   Visit PureSourceCode
</a>

You find the code for that here:

// Piwik
var _paq = _paq || [];
_paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
_paq.push(["setCookieDomain", "*"]);
_paq.push(["setDomains", ["*"]]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function () {
    var u = "//a.esia.info/";
    _paq.push(['setTrackerUrl', u + 'piwik.php']);
    _paq.push(['setSiteId', 28]);
    var d = document, g = d.createElement('script'), s = d.getElementsByTagName('script')[0];
    g.type = 'text/javascript'; g.async = true; g.defer = true; g.src = u + 'piwik.js'; s.parentNode.insertBefore(g, s);
})();

// Google analytics
(function (i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
        (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date(); a = s.createElement(o),
    m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-XXXXXXXX-1', 'auto');
ga('send', 'pageview');

if (typeof jQuery != 'undefined') {
    jQuery(document).ready(function ($) {
        var filetypes = /\.(zip|exe|dmg|pdf|doc.*|xls.*|ppt.*|mp3|txt|rar|wma|mov|avi|wmv|flv|wav)$/i;
        var baseHref = '';
        if (jQuery('base').attr('href') != undefined) baseHref = jQuery('base').attr('href');

        jQuery('a').on('click', function (event) {
            var el = jQuery(this);
            var track = true;
            var href = (typeof (el.attr('href')) != 'undefined') ? el.attr('href') : "";
            var isThisDomain = href.match(document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0]);
            if (!href.match(/^javascript:/i)) {
                var elEv = []; elEv.value = 0, elEv.non_i = false;
                if (href.match(/^mailto\:/i)) {
                    elEv.category = "email";
                    elEv.action = "click";
                    elEv.label = href.replace(/^mailto\:/i, '');
                    elEv.loc = href;
                }
                else if (href.match(filetypes)) {
                    var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                    elEv.category = "download";
                    elEv.action = "click-" + extension[0];
                    elEv.label = href.replace(/ /g, "-");
                    elEv.loc = baseHref + href;
                }
                else if (href.match(/^https?\:/i) && !isThisDomain) {
                    elEv.category = "external";
                    elEv.action = "click";
                    elEv.label = href.replace(/^https?\:\/\//i, '');
                    elEv.non_i = true;
                    elEv.loc = href;
                }
                else if (href.match(/^tel\:/i)) {
                    elEv.category = "telephone";
                    elEv.action = "click";
                    elEv.label = href.replace(/^tel\:/i, '');
                    elEv.loc = href;
                }
                else if (href.match(/^call\:/i)) {
                    elEv.category = "telephone";
                    elEv.action = "click";
                    elEv.label = href.replace(/^call\:/i, '');
                    elEv.loc = href;
                }
                else track = false;

                if (track) {
                    TrackEvent(elEv.category.toLowerCase(), elEv.action.toLowerCase(), elEv.label.toLowerCase(), elEv.value);
                    if (el.attr('target') == undefined || el.attr('target').toLowerCase() != '_blank') {
                        setTimeout(function () { location.href = elEv.loc; }, 400);
                        return false;
                    }
                }
            }
        });
    });
}

/* Tracking events */
function TrackEvent(category, action, label, value) {
    // add to Google Analytics
    ga('send', 'event', category, action, label, value);
    // add to Westhill Analtics
    _paq.push(['trackEvent', category, action, label, value]);
}

In attach the code trackingGenerator.js (4KB)

How to Track Downloads & Outbound Links in Google Analytics

Since Google Analytics does not track file downloads, email, telephone or other outbound link clicks automatically, we saw an opportunity to provide this code to the community.

Dynamically Track Downloads & Other External Links

For those who have a lot of links and would like to dynamically detect clicks on links to file downloads, we have provided updated code below.  As before, this code requires the jQuery JavaScript library to be set before the code.

We have updated the code to make it more manageable and easier to extend.  In addition, we are using the jQuery on() method for attaching the click event handler to links.  Since we are using the on() method you will need to use jQuery v1.7+.  If you are using an earlier version of jQuery the .live() method can be used instead.

The primary benefit of using the on() method is performance.  Instead of looping through all ‘a’ elements on a page after the page loads (takes processing power on pages with lots of links), we instead listen for any clicks on the ‘a’ elements and invoke our custom JavaScript on the fly.

Again, feel free to customize this code to suite your needs.  It can be placed in its own .js file and should be placed in the <head> of your pages.  This script automates the following:

  • Tracks file downloads as events for the following extensions: .zip, .exe, dmg, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .txt, rar, wma, mov, avi, wmv, flv, wav (again feel free to modify the list)
  • Tracks outbound clicks as events if the href value contains http:// or https:// and the domain value doesn’t match the current domain
  • Tracks mailto email clicks
  • Tracks Tel telephone clicks
<script type="text/javascript">
if (typeof jQuery != 'undefined') {
  jQuery(document).ready(function($) {
    var filetypes = /\.(zip|exe|dmg|pdf|doc.*|xls.*|ppt.*|mp3|txt|rar|wma|mov|avi|wmv|flv|wav)$/i;
    var baseHref = '';
    if (jQuery('base').attr('href') != undefined) baseHref = jQuery('base').attr('href');

    jQuery('a').on('click', function(event) {
      var el = jQuery(this);
      var track = true;
      var href = (typeof(el.attr('href')) != 'undefined' ) ? el.attr('href') :"";
      var isThisDomain = href.match(document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0]);
      if (!href.match(/^javascript:/i)) {
    	var elEv = []; elEv.value=0, elEv.non_i=false;
        if (href.match(/^mailto\:/i)) {
          elEv.category = "email";
          elEv.action = "click";
          elEv.label = href.replace(/^mailto\:/i, '');
          elEv.loc = href;
        }
        else if (href.match(filetypes)) {
          var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
          elEv.category = "download";
          elEv.action = "click-" + extension[0];
          elEv.label = href.replace(/ /g,"-");
          elEv.loc = baseHref + href;
        }
        else if (href.match(/^https?\:/i) && !isThisDomain) {
          elEv.category = "external";
          elEv.action = "click";
          elEv.label = href.replace(/^https?\:\/\//i, '');
          elEv.non_i = true;
          elEv.loc = href;
        }
        else if (href.match(/^tel\:/i)) {
          elEv.category = "telephone";
          elEv.action = "click";
          elEv.label = href.replace(/^tel\:/i, '');
          elEv.loc = href;
        }
        else track = false;

       	if (track) {
          _gaq.push(['_trackEvent', elEv.category.toLowerCase(), elEv.action.toLowerCase(), elEv.label.toLowerCase(), elEv.value, elEv.non_i]);
          if ( el.attr('target') == undefined || el.attr('target').toLowerCase() != '_blank') {
            setTimeout(function() { location.href = elEv.loc; }, 400);
            return false;
	  }
	}
      }
    });
  });
}
</script>

The script sets download, email and tel link clicks as interaction events while the external site clicks are non-interaction which can be adjusted if desired.

As before, the script will detect if the link is opening in a new window or not and automatically uses setTimeout() for 400ms if you are not. This is to allow time for the hit request to process before taking the user to the new page.

Inline Download & Other External Links Tracking

If you’d rather not use the above method to place a single javascript file on your site and automate the tracking for all link elements, you can use the manual inline approach by tagging each link element individually.  The inline approach can be time consuming and is not scalable.

The original syntax for adding the code inline remains the same.

New window/tab
For links that open a new window or tab (such as using target=”_blank” for example) you will want to use the code below:

<a onclick="_gaq.push(['_trackEvent','Download','PDF','Description']);" 
   href="my-file.pdf" target="_blank">
   Download my file
</a>

In current window
For links that open within the same window, replacing the current page, you will want to use the code below:

<a onclick="var that=this;_gaq.push(['_trackEvent','Download','PDF',this.href]);
   setTimeout(function(){location.href=that.href;},400);
   return false;" 
   href="my-file.pdf">
   Download my file
</a>

These type of links require a slight delay to allow time for the hit request to process before taking the user to the new page.

Detailed Download & External Link Reports

After all of your hard work you will have event tracking reports with neatly organized data around file downloads, external link, email link, and telephone link clicks.  From these reports you can gauge the usage and usefulness of your file downloads and various links.

events_report1

 

By diving into the download category and selecting event label as the primary dimension you are able to see a report on all of the individual files downloaded from your site.

events_downloads

 

Lastly, since events are associated with the page they were fired on, you are able to apply a secondary dimension of page to find out which page contained the download or external link click that occurred.

Advertsing

125X125_06





TagCloud

MonthList

CommentList