Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bigdawggi/1387334 to your computer and use it in GitHub Desktop.
Save bigdawggi/1387334 to your computer and use it in GitHub Desktop.
jQuery-based outbound link tracking with cases for new window as well as same window locations
@brodseba
Copy link

brodseba commented Apr 4, 2013

The problem with window.open is that the referrer will be lost. A better solution is to use onmousedown instead of onclick. Having done some tests, I know this work better that using window.open or using setTimeout. You got some false positive from people clicking the right mouse button and not choosing "Open in new tab" or "Open in new window", but onclick doesn't always fire for middle and right click on all browser. It's a choice between the lesser of two evils here.

@brodseba
Copy link

brodseba commented Apr 4, 2013

jQuery(function($){
  $('a:not([href*="' + document.domain + '"])').mousedown(function(event){
    // Just in case, be safe and don't do anything
    if (typeof _gat == 'undefined') {
      return;
    }

    var link = $(this);
    var href = link.attr('href');
    var noProtocol = href.replace(/http[s]?:\/\//, '');

    // Track the event
    _gat._getTrackerByName()._trackEvent('Outbound Links', noProtocol);
   });
});

@zaaccdesignweb
Copy link

Hi,

onmousedown worked great for me

<a href="#" onmousedown="_gaq.push(['_trackEvent', 'Videos', 'Play', 'Baby\'s First Birthday']);">My Link</a>

Better the than the Google code: Outbound links https://support.google.com/analytics/answer/1136920?hl=en.

@satanasov
Copy link

There is a bit of a setback in the last script. If the address is using relative domain it will be counted as externel. We can do a simpe check:

jQuery(function($){
  $('a:not([href*="' + document.domain + '"])').mousedown(function(event){
    // Just in case, be safe and don't do anything
    if (typeof _gat == 'undefined') {
      return;
    }

    var link = $(this);
    var href = link.attr('href');
    if (href.charAt(0) != '.' && href.charAt(0) != '#' && href.charAt(0) != '/) {
       var noProtocol = href.replace(/http[s]?:\/\//, '');

       // Track the event
       _gat._getTrackerByName()._trackEvent('Outbound Links', noProtocol);
    }
   });
});

This will check if the first char is a part of a relative domain name.

@ckihneman
Copy link

mousedown doesn't mean they clicked the link. You could get false data if they click on the element and drag away (not finishing the mouseup on the element).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment