JavaScript - - By Craig Buckler

How to Track Outbound Links in Google Analytics

Google Analytics provides an overwhelming quantity of information. If you do nothing but add the tracking script to your pages, you’ll be faced with an endless stream of data and reports about user activity on your site. However, while Analytics shows exit pages it won’t tell you which links users clicked to leave your site. In this article we’ll discover how to add outbound link tracking.

Does Google Record Outbound Links?

Probably. If you’re linking from one site using Analytics to another using Analytics Google could record that relationship. Unfortunately, reports would be misleading if one or more outbound sites didn’t use Analytics.

Google has additional means of collecting data: you can gather a lot of statistics when you own the top browser and search engine! But we’re then moving away from on-site Analytics into more dubious territory; Google wouldn’t necessarily want to share that data.

Fortunately, we can gather outbound link details ourselves.

Upgrade to Universal Analytics First!

Before we go any further, you must upgrade to Universal Analytics. Google has possibly started this process for you but the tracking code must be updated on your website pages. It’s a pain, but the outbound link tracking code shown below won’t work without it. (It could be made to work with legacy Analytics, but it’ll eventually stop working so it’s best to upgrade now.)

Custom Event Tracking

Analytics supports event tracking. Typically, it’s used for recording on-page JavaScript-controlled interactivity such as opening a widget or making an Ajax call. We can use event tracking to record outbound links but there are a number hurdles to overcome:

  • the event must be recorded on all browsers and not impede navigation
  • we should not need to manually identify or attach separate handlers to every outbound link, and
  • we must ensure the event is recorded before the outbound page starts to load.

The solution…

  1. We’ll attach a click event handler to the body element. This will receive an clicked-link events as they bubble up through the DOM.
  2. We can detect whether a link will open a page on a domain which is different to ours. If it’s an outbound link, we’ll cancel the click event and initiate Analytics event tracking.
  3. In the background, Analytics sends data by requesting an image beacon. Once the call is complete, it can run a callback function so we can redirect to the outbound page.
  4. We need to be careful and ensure tracking never stops user navigation even on failure. The process must be fast, not handle clicks which have been deactivated by other processes and ensure links work even if the Analytics event fails.

We want tracking to work everywhere so I recommend using a library with robust cross-browser event handling. I’ll use jQuery 1.x for this example since most sites use it but you can substitute a lightweight option such as min.js, Zepto.js, Minified.js or your own event handling functions.

The full code is shown below. This can be added to existing JavaScript files or in a script block as long as it’s loaded somewhere within the HTML body (ideally, just before the closing tag). jQuery (or your alternative) must be loaded first although the Google Analytics tracking code can appear anywhere on the page.

/* Track outbound links in Google Analytics */
(function($) {

  "use strict";

  // current page host
  var baseURI = window.location.host;

  // click event on body
  $("body").on("click", function(e) {

    // abandon if link already aborted or analytics is not available
    if (e.isDefaultPrevented() || typeof ga !== "function") return;

    // abandon if no active link or link within domain
    var link = $(e.target).closest("a");
    if (link.length != 1 || baseURI == link[0].host) return;

    // cancel event and record outbound link
    e.preventDefault();
    var href = link[0].href;
    ga('send', {
      'hitType': 'event',
      'eventCategory': 'outbound',
      'eventAction': 'link',
      'eventLabel': href,
      'hitCallback': loadPage
    });

    // redirect after one second if recording takes too long
    setTimeout(loadPage, 1000);

    // redirect to outbound page
    function loadPage() {
      document.location = href;
    }

  });

})(jQuery); // pass another library here if required

The event is recorded with the category name ‘outbound’, action name ‘link’ and the value set to the URL of the outbound page. You can modify these in the ga call if necessary (lines 24 to 26).

Once implemented, visit your site and click a few outbound links. You should see the activity in the Analytics Real-Time > Events panel. Further data will appear in the Behavior > Events pane after a few hours.

Please use the code as you wish.

Sponsors