Menu

Sponsored By: Password Angel - Share passwords, API keys, credentials and more with secure, single-use links.

How To: Track Outbound Links

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.

Enjoyed this article?

Thank you for reading this article! If you found the information valuable and enjoyed your time here, consider supporting my work by buying me a coffee. Your contribution helps fuel more content like this. Cheers to shared knowledge and caffeine-fueled inspiration!

Buy me a coffee

Originally published at https://chrisshennan.com/blog/how-to-track-outbound-links

Subscribe to my newsletter...

... and receive the musings of an aspiring #indiehacker directly to your inbox once a month.

These musings will encompass a range of subjects such as Web Development, DevOps, Startups, Bootstrapping, #buildinpublic, SEO, personal opinions, and experiences.

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