Nick Hammond

Software Developer, Cyclist, & Traveler.

Simpler Outbound Event Tracking With Google Analytics

In tracking

I started moving around my navigation and omni-present social icons when I realized I didn’t really have any concrete data on what people were actually using. It’s pretty simple to track clicks to external links as events in Google Analytics but even easier via beacon transport.

The beacon transport option with Google Analytics is utilizing a new browser method internally, navigation.sendBeacon(). This method was implemented to support sending small amounts of data asynchronously from browser to server and if you look through the documentation it’s intention was exactly for this type of interaction, tracking analytics on page unload.

For browsers that don’t yet support the new sendBeacon() method, it’ll fall back to an xhr(AJAX style) request. The best part about setting this up with an event tracker though is being able to specify the callback. That way you’re able to easily track and then trigger the click. Since I’ll be using this for outbound link tracking and attributing a source location on the page any link that’s external with the data-source attribute will be properly tracked.

  $('a').click(function(e) {
    if (!$(this).prop("hostname").match(location.hostname)) {
      href = $(this).prop("href")
      source = $(this).data("source")
      if (source == null) {
        source = ''
      ga('send', 'event', 'External', href, source, {
        'transport': 'beacon',
        'hitCallback': function(){document.location = href;}

Here’s a link on the page to track when someone clicks the subscribe link and the source is navigation since it’s the link in the navigation section.

<a href="" data-source="navigation">Subscribe</a>

Here we’re binding on the click event for any link that goes to an external domain. We grab the data-source attribute and set that as the source and then for our hitCallback we finally take the user to the link. Since we’re using the hitCallback we don’t need to utilize a timeout or try and trick the browser into tracking the link properly, Google will just call this function after it’s successfully tracked the event.

P.S. We should keep in touch, subscribe below.