Fragmented Thought

Tracking External Links



Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

Google Analytics doesn't track external page links by default, you have to setup a small bit of javascript to delay the website exit, and trigger a virtual page hit. The code for doing that involves a small bit of jQuery, and the newer version of the Google tracking code.

Google Tracking Code

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("UA-xxxxxx-x"); pageTracker._trackPageview();

Create the following function, and call it in your $(document).ready():

function initExternalTrackingLinks(){ // Creating custom :external selector $.expr[':'].external = function(obj){ return !obj.href.match(/^mailto:/) && (obj.hostname != location.hostname); }; // Add 'external' CSS class to all external links, and augment behavior $('a:external').addClass('external').click(function(e){ try { e.preventDefault(); // Tested in IE8, Chrome, and FF 3.6 to override the onclick attribute. if(pageTracker){ pageTracker._trackPageview('/outgoing/'+ $(this).attr('href')); } setTimeout('document.location = "' + $(this).attr('href') + '"', 100); }catch(err) { document.location = $(this).attr('href'); } }); } $(document).ready(){ initExternalTrackingLinks(); }