Showing posts with label google analytics. Show all posts
Showing posts with label google analytics. Show all posts

Sunday, August 24, 2014

Tracking outbound links with google analytics, without annoying middle-clickers

As a quick and dirty solution I just added google analytics tracking of outbound links. It was really easy as I just borrowed a piece of code from this blog (kudos!). Everything went fine and the stats started coming in.

But when I later visited the site myself I realized something awful. Since I'm a obsessive middle-clicker opening all potentially interesting links in new tabs I ran into the issue immediately. It opens my middle-clicks in the same tab, transforming my middle-clicks to left-clicks.

Further googling explained everything. Many have written scripts like the one I picked and some have already considered this issue. So I read them all and improved the script I had stolen already. Here it is. Please comment if you think there's something wrong with it!


(function($) {
  "use strict";
  // current page host
  var baseURI = window.location.host;
  // click event on body
  $("body").on("click", function(e) {
    // abandon if link already aborted or analytics is not available
    if (e.isDefaultPrevented() || typeof ga !== "function") return;
    // abandon if no active link or link within domain
    var link = $(e.target).closest("a");
    if (link.length != 1 || baseURI == link[0].host) return;
    var normalClick = !e.metaKey && !e.crtlKey && e.which == 1;
    var href = link[0].href;
    var opts = {'hitType': 'event','eventCategory': 'outbound',
      'eventAction': 'link','eventLabel': href
    }
    if (normalClick) {
     // cancel event and record outbound link
     { opts.hitCallback = loadPage };
     e.preventDefault();
     ga('send', opts);
     // redirect after one second if recording takes too long
     setTimeout(loadPage, 1000);
    } else {
     // Just send the event
     ga('send', opts);
    }
    // redirect to outbound page
    function loadPage() {
      document.location = href;
    }
  });
})(jQuery);