Tracking Outbound Links with Google Analytics

analytics-events

I’ve recently been working on a website that needs to track external link clicks in Google Analytics. This is something that the WordPress.com stats plugin does by default, but not Google. In order to track external links with Google Analytics, you’ll need to set up a custom tracker event.

The method suggested by Google involves manually applying code to each link. This is fine if you want to just track a few specific links, but jQuery is more useful if you want to track every external link on the page.

Custom Tracking Events

The meat of the custom event is this line (which should be fired when an external link is clicked) is:

_gaq.push(['_trackEvent', 'Outbound Links', e.currentTarget.host, url, 0]);
  • “Outbound Links” is the category of events to track
  • “e.currentTarget.host” is the “action”, in this case, the domain the user is clicking to.
  • “url” is the “label”, which I use to send the full url of the external link.

If you’re unfamiliar with custom events, here’s the docs page at Google.

Code for Detecting and Tracking Outbound Link Clicks

This code snippet is highly commented and peppered with console.logs so that you can verify it’s working correctly and see how it works. It should only be used in development environments- there’s a compressed version in the next section for use on live sites.

// Outbound Link Tracking with Google Analytics
// Requires jQuery 1.7 or higher (use .live if using a lower version)
// For more info see: http://support.google.com/googleanalytics/bin/answer.py?hl=en&answer=55527
$("a").on('click',function(e){
		var url = $(this).attr("href");
		// Console logs shows the domain name of the link being clicked and the current window
		console.log('e.currentTarget.host: ' + e.currentTarget.host);
		console.log('window.location.host: ' + window.location.host);
		// If the domains names are different, it assumes it is an external link
		// Be careful with this if you use subdomains
		if (e.currentTarget.host != window.location.host) {
			console.log('external link click');
			// Outbound link!  Fires the Google tracker code.
			_gaq.push(['_trackEvent', 'Outbound Links', e.currentTarget.host, url, 0]);
  		// Checks to see if the ctrl or command key is held down
		// which could indicate the link is being opened in a new tab
		if (e.metaKey || e.ctrlKey) {
			console.log('ctrl or meta key pressed');
			var newtab = true;
		}
		// If it is not a new tab, we need to delay the loading
		// of the new link for a just a second in order to give the
		// Google track event time to fully fire
		if (!newtab) {
			console.log('default prevented');
			e.preventDefault();
                        console.log('loading link after brief timeout');
			//setTimeout('document.location = "' + url + '"', 100);
		}
	}
	else {
		console.log('internal link click');
	}
});

Compressed Version

This is the same code as above, but with comments and console.logs stripped out:

// Outbound Link Tracking with Google Analytics
// Requires jQuery 1.7 or higher (use .live if using a lower version)
$("a").on('click',function(e){
	var url = $(this).attr("href");
	if (e.currentTarget.host != window.location.host) {
		_gaq.push(['_trackEvent', 'Outbound Links', e.currentTarget.host, url, 0]);
		if (e.metaKey || e.ctrlKey) {
		     var newtab = true;
		}
		if (!newtab) {
		     e.preventDefault();
		     setTimeout('document.location = "' + url + '"', 100);
		}
	}
});

Viewing the Results

To see if your custom tracking events are firing correctly, check your Google Analytics dashboard under “Content > Events > Overview”. It may take a couple hours before you start to see the results. In this screenshot you can clearly see when the tracking began:

In WordPress

If you are using a plugin for Google Analytics, like Google Analyticator, there is a settings fields where you can add javascript to be included with the tracker. You can also just include it with your other scripts.

Another option to track links easily in WordPress is to use the stats from Jetpack, which give you outbound click data by default.

About Devin

I'm a WordPress developer based in Austin, Texas. Follow my projects on GitHub, or more general WordPress ramblings as @devinsays on twitter.

28 Responses

  1. Nice clean quick code! However, it does not appear to be respecting the target attribute of the link. Specifically, target=_blank.

    I’d did this quick mod…

    Added : var target = $(this).attr(“target”);
    and Changed : if (e.metaKey || e.ctrlKey || target==”_blank”)

  2. Do you know is there is a way to track email clicks for WordPress.COM? Ie, if I want to market my site to specific people via email, but I want to know who clicked through (or even IF people clicked through via an email link), is there a way to do this?
    Thanks!
    Kristen

  3. Paul

    Thanks so much for your contribution, Devin!

    If anyone else has trouble implementing this, note that you need to put the code within the following:

    $(function()
    {
    // Paste the jQuery code here. :-)
    });

    Figured this out by examining this: http://jsfiddle.net/Shef/gE7XS/

  4. Hello,
    Maybe someone can help. I have tried above solution (condensed code) in magento backend in the footer with miscelanous scripts. But it does not work. The code is actually displayed on the site. Something seems missing. some closing or starting character?

    Thanks

  5. Hello,
    I wanted to use this idea on a magento website. It took me some time to make it work and use the magento backoffice for adding the code. With some advise of Devin and collegue of mine, i got it right.

    I added the following code in the footer/at the end of the page.

    $(function(){
    $(“a”).on(‘click’,function(e){
    var url = $(this).attr(“href”);
    if (e.currentTarget.host != window.location.host) {
    _gat._getTrackerByName()._trackEvent(“Outbound Links”, e.currentTarget.host, url, 0);
    if (e.metaKey || e.ctrlKey) {
    var newtab = true;
    }
    if (!newtab) {
    e.preventDefault();
    setTimeout(‘document.location = “‘ + url + ‘”‘, 100);
    }
    }
    });
    });

    In this example the jquery ir sourced from google. But you could store that locally.

    The endresult is that all outbound links on my site are now measured properly without me having to add code to each link individually.

  6. Hi Devin,

    please, modify the script a this line:

    if (!newtab) {

    by this one:

    if (!newtab && e.which!=2) {

    It will prevent to change location to the middle mouse event (open in new tab)

    Thanks for the currentTarget tip, I’m trying to track the subdomains as external links.

  7. Subdomain links are measured with this script but in my case are showing up as events with a code like for example:E71121. Any suggestion to get this converted to a understandable name would be great.

  8. What about identifying multiple links that go to same location. For example. My client has many pages where the text contains several inline links to other parts of their site such as the glossary. Also what about the identifying any links will they all just be bucketed under “outbound links”?

    Thanks,

    Mary

  9. Ohad

    I used $(document).on(‘mousedown’,’a’,function(e){
    /* rest of the code here*/
    that way I could also track the right and middle clicks
    also attach the event to the a didn’t worked for me all the time maybe because I have a lot of other events attach to the a’s so though attaching the event to the document is a bit slower it still much safer . (and for my needs it was worth the cost)

    1. ohad

      another thing
      in order for this code to work in ie 8 I changed from e.currentTraget.host to e.currentTarget.hostname , (worked for all major browsers) another option is to remove the port number e.currentTarget.host.replace(‘:80′,”);

  10. Joe

    Hi Ohad
    The “rest of the code here” doesn’t seem to be appearing. Could you please upload to somewhere?

    Can anyone else provide a full solution/code for this?
    Thanks

  11. S├ębastien Brodeur

    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.


    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);
    });
    });

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>