How to Track Downloads in with Universal Google Analytics

The code below is a modification on the code mentioned in this article by Blast Analytics about how to track downloads in the Events tab in Google Analytics. The code they have in their article works only with Analytics Classic - this has been modified to use the send function available in the new analytics tracking code.


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

$('a').on('click', function(event) {
  var el = $(this);
  var track = true;
  var href = (typeof(el.attr('href')) != 'undefined' ) ? el.attr('href') :"";
  
  //console.log(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) {
      
      ga('send', {
        hitType: 'event',
        eventCategory: elEv.category.toLowerCase(),
        eventAction: elEv.action.toLowerCase(),
        eventLabel: elEv.label.toLowerCase(),
        eventValue: elEv.value
      });

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

Comments, Thoughts?

For now, please find me on Twitter (@erickarbe) and let me know what's on your mind. Or, find me on Google.