How To: Track Outbound Links

2nd November 2015

Great! You have got visitors on your website, you can see they viewed several articles, but where did they go next?

Everyone wants to know why their visitors left their website and this might be for a number of reasons including:-

  • Creating new content around the topics which your visitors go on to read on other sites
  • Identifying influencers who could help promote your content further
  • Identifying possible affiliate marketing opportunities Whatever the reason, we can enable outbound link tracking really easily using the script below:-
/*
 * Track outbound links
 */

$(function() {
    // Track outbound links
    if(typeof(ga) !== 'undefined') {
        // Track outbound links        
        $('a[href*=http]').on('click', function(e) {

            var el = $(this);
            var href = el.attr('href');
            var http = 'http://' + window.location.host;
            var https = 'https://' + window.location.host;

            // If the link does not belong to the site then record it
            if(href.substr(0, http.length) != http && href.substr(0, https.length) != https) {
                var parts = href.split('/');
                parts.splice(3);
                var domain = parts.join('/');

                ga('send', 'event', 'Outbound Link', domain, href);
            }
        });
    }
});

The code above checks to make sure the URL is not for the same domain you are looking at and records:-

  • The domain of the URL into the Event Action attribute
  • The full URL itself into the Event Label attribute

So now we can see which websites and pages we refer the most traffic to.

Liked this article?

Subscribe to my newsletter and get the ramblings of a wannabe #indiehacker straight in your inbox once a month. Ramblings will cover a variety of topics including:-

Web Development, DevOps, Startups, Bootstrapping, #buildinpublic, SEO, opinion and personal experience.

I won't send you spam and you can unsubscribe at any time.