Google Analytics Hack: Track Outbound Links In 2 Easy Steps

Reading time: About 2 minutes

Inbound links answer a basic question: How do people find my site? But that’s just half the equation. People come and go. Where are they all going? Are people leaving your website because they aren’t engaged or because they are following one of your outbound links?

Those outcomes suggest two different things about the effectiveness of your website. In the first case your website isn’t effective; in the second case your visitors read enough to at least follow your links.

Outbound links are not tracked by Google Analytics despite their potential value. That is to say without a little programming wizardry and Google Analytics hackery [insert geek smirk here].

Step 1: Programming wizadry with Javascript

The first step is to add some javascript magic to each of your webpages. You can either copy and paste the following source code into one of your existing javascript files, or you can download a copy of the source code here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
if(typeof jQuery == 'function') { /* use jQuery if it exists because it is a more elegant solution */
	jQuery(function () {
		jQuery('a:not([href*="' + document.domain + '"])').click(function () {
			pageTracker._trackPageview('/outgoing/' + jQuery(this).attr('href'));
		});
	});
}
else { /* use regular Javascript if jQuery does not exist */
	window.onload = function () {
		var links = document.getElementsByTagName('a');
		for (var x=0; x < links.length; x++) {
			links[x].onclick = function () {
				var mydomain = new RegExp(document.domain, 'i');
				if(!mydomain.test(this.getAttribute('href'))) {
					pageTracker._trackPageview('/outgoing/' + this.getAttribute('href'));
				}
			};
		}
	};
}

The above code works by telling Google Analytics to record a page view for every outbound link. As a result, Google sees outbound links as another page view on your website under the subdirectory /outgoing/. So, for example, if someone clicks a link to http://briancray.com/ on your website, Google Analytics will record a page view of /outgoing/http://briancray.com/. See the example screenshot below taken from the Content � Overview section of Google Analytics:

/outgoing/http://topfollowfriday.com/ has 9 pageviews

Step 2: Google Analytics hackery to filter outbound links

You may have already realized that the above script introduced a slight problem: Your page views now account for actual page views as well as outbound links. If this doesn’t concern you, you can quit reading now and enjoy the script. If this does concern you, here’s step–by– screenshots to explain how to filter outbound links in Google Analytics:

Screenshot 1

Click All Visits

Screenshot 2

Create New

Screenshot 3

Drag Page

Screenshot 4

Change Filter

Screenshot 5

Name It

Screenshot 6

Apply Filter

Once you apply your new custom segment in Google Analytics, you will only see traffic details for the outbound links. To filter out the outbound links and see only normal traffic, you would set the “Condition” dropdown to “Does not contain” instead of “Starts with” as seen in screenshot #4.

That’s it!

I hope you enjoyed this little Google Analytics hack and Javascript magic. If you enjoy javascript, jquery, and pretending to be a real hacker, feel free to read my other entries and subscribe to my blog.

25 comments skip to comment form

  1. Julie M. Townsend said— 2 days later

    Why don’t you just use the onclick() event to call the GA trackpageview function? It is a lot simpler that way…

    #1
  2. Brian Cray said— 4 days later

    @Julie M. Townsend
    This tutorial actually uses the onclick() function, and does so in the most non-obtrusive way possible. With my script, it’s a simple plug-n-play away.

    #2
  3. Kurt Avish said— 4 days later

    Very nice hack indeed. Thanks. Gonna have a look right now :D

    #3
  4. Cyrus said— 4 days later

    Hi friends, free online youtube downloader check its out at youtubedownloader{dot}lamphunengineer{dot}com ,,, Enjoys you vid

    #4
  5. HB said— 2 weeks later

    I might be missing something, but it looks like the example uses mydomain.match, but it should either use mydomain.test(this.getAttribute(‘href’)) or this.getAttribute(‘href’).match(mydomain).

    At least, when I tried as-is it threw errors about match not belonging to mydomain. .test instead of .match works fine.

    Cool hack, regardless.

    #5
  6. Dave said— 1 month later

    Hi,

    I’ve gone through this tutorial for capturing outbound links. Analytics is showing 0 hits for outbound. However, I know we’ve had outbound links on the pages I’ve placed the javascript on. Any ideas what could be wrong?
    Here is one of the pages I’m tracking.
    http://www.floppyseat.com/product_descriptions/GeoDots.htm

    Thanks.

    #6
  7. Brian Cray said— 1 month later

    HB: Thanks for the tip… updated this tut’s script

    Dave: Try using the updated code and let me know if you have better luck. Cheers!

    #7
  8. Dave said— 2 months later

    Hey, what do you know. It works. Funny how you do all the hard work and I get the credit for tracking!

    #8
  9. Brian Cray said— 2 months later

    Awesome Dave! You do get the credit, but I don’t share all of my secrets :)

    #9
  10. Dave said— 2 months later

    HI Brian,

    So I have a question. If I’ve only installed the javascript on certain pages, why do other pages in my site show outbound links? Perhaps I have my definition of outbound links wrong? But there are only 3 pages on my site that have a link to an outside site that I want to track.
    Thanks,
    Dave

    #10
  11. ugst said— 2 months later

    I have followd step 2 and have applied it to my site. But where can I see the report for outgoing links.

    #11
  12. WRG said— 2 months later

    hello i added the code at the end of the google analytics code, beofre the tage. Will that suffice?

    #12
  13. Brian Cray said— 2 months later

    WRG:

    I would say you have to monitor whether it works. Check in a week to see if you have outbound links in Google Analytics

    #13
  14. diego said— 5 months later

    Great idea, on comment do. I would move the domain check out of the onclick function, and only set a onclick function when the link is for domain is not the current domain.

    #14
  15. Spewf said— 6 months later

    I added the exact code from above but i still get 0 page views. When looking at the source this is what it says for one specific link, is this right? onclick=”return TrackClick(‘http%3A%2F%2Fthechive.com%2F2009%2F09%2Fgot-your-attention-good-now-send-us-your-damn-photos%2F’,'The+Chive’)”

    Thanks

    #15
  16. David Merry said— 6 months later

    Hi Brian,

    Thanks for the tips, I have used them on my website and have yet to see if they work!

    Anyhow, I just took a look through the rest of your blog and some of the posts are outstanding. I will definitely be subscribing!

    Thanks,

    Dave

    #16
  17. Luke Eales said— 6 months later

    Bear in mind that this technique will artificially inflate your pageview count. This may or may not matter to you. If it does, then you’ll probably want to create a new profile for accurately tracking *real* pageviews, as opposed to *virtual* pageviews, which will contain a filter removing any pageviews with /outgoing/ present.

    #17
  18. Greg said— 7 months later

    Thats an excellent script and just what i was looking for after much time surfing about, thanks a lot

    #18
  19. alhasib said— 10 months later

    Great script! This is exactly what I have been looking for to track some outgoing banner ads that I have on my site.

    #19
  20. Gavin Doolan said— 11 months later

    Thanks Brian you have saved me loads of time.

    This article may be before the _trackEvent() method was released. But in my opinion Event Tracking is far more appropriate for tracking outbound links than _trackPageview().

    See: http://code.google.com/apis/analytics/docs/gaJS/gaJSApiEventTracking.html

    Eg: _trackEvent(category, action, opt_label, opt_value)

    So with an outbound link it might look something like this:

    _trackEvent(“links”, “outbound”, “link name”, 2)

    Where the category = links
    The action = outbound
    The label = link name
    Value = 2

    This is also more robust because technically you could assign a value to each outbound click (useful for affiliates / shopping compare sites etc..) in the example above I specified a value of 2.

    If your anchor tag has a name attribute or title for that matter, you could pass in that value for the link name to help identify it, or you could just take the href.value

    eg: link name

    Hope that helps.

    #20
  21. Canton Becker said— on March 14, 2009 later

    Hi, this is working pretty great so far, except that when I use analytics to “drilldown” to /outgoing I see over 8,000 hits to / (slash) — as in, outgoing/

    See: http://cantonbecker.com/random/outgoing.png

    We’re trying out this code on http://asiafoundation.org

    I can’t figure out what might be causing this. I expected out pagecount to inflate somewhat, but this looks like some huge portion of our internal clicks counting as bogus /outgoing clicks. Our pagecounts have *doubled* since dropping in this code.

    Thanks for any ideas!

    #21
  22. mev said— on March 14, 2009 later

    Using onClick you may lose some information. If you click the right button and select the context menu “Open in new tab” – event onClick does not work, Google Analytics will not count anything, you lose some visits or events.
    I posted recenlty about it http://chenado.net/en/1040.html

    #22
  23. 1shot1kill said— on March 14, 2009 later

    Hey Gavin Doolan – the problem with your method is imagine you have hundreds of links AND they change monthly. Can you imagine hand coding hundreds of new name attribute or titles to each and every single link… UGH!

    #23
  24. jaamit said— on March 14, 2009 later

    This is exactly what I have been looking for, a very neat solution. I know event tracking is ‘neater’ for tracking outbound links now but the one problem with it is GA still don’t allow setting events as Goals, which is something I often want to do with outbound links.

    However I need to convert this so it will work with the new Async tracking code which is now standard. Can you confirm if this code is correct?

    Jquery:
    _gaq.push(['_trackPageview', ('/outgoing/' + jQuery(this).attr('href'))]);

    JavaScript:
    _gaq.push(['_trackPageview', ('/outgoing/' + this.getAttribute('href'))]);

    Appreciate any help you can give with this!!

    #24
  25. Brian Brown, Ph.D. said— on March 14, 2009 later

    Likewise!

    #25
  26. Respond to this post—

Return to navigation
231