target=_blank doesn't work with GA outbound link tracking

Charles Ingalls picture Charles Ingalls · Nov 14, 2014 · Viewed 11k times · Source

I want to track clicks on outbound links and implemented the following code:

GA code

var trackOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {'hitCallback':
     function () {
     document.location = url;
     }
   });
}

Links

<a class="postLinks" href="<?php if (get_field('source_link')) echo get_field('source_link'); ?>" onclick="trackOutboundLink('<?php if (get_field("source_link")) echo get_field("source_link"); ?>'); return false;"><?php the_title(); ?></a>

target=_blank

I add the target=_blank attribute via jQuery based on whether the visitor to the website ticks a checkbox or not (the selection is then stored in a cookie). However, if I choose to open the outbound link in a new window it doesn't work. When ticking the checkbox it does correctly add the target attribute to the link but when I click on the link it opens it in the same window.

Links with target attribute

<a class="postLinks" href="<?php if (get_field('source_link')) echo get_field('source_link'); ?>" onclick="trackOutboundLink('<?php if (get_field("source_link")) echo get_field("source_link"); ?>'); return false;" target="_blank"><?php the_title(); ?></a>

Any idea?

Answer

alexp picture alexp · Nov 14, 2014

Having target="_blank" on a link will not do anything if you're changing the page URL via JavaScript by changing document.location.

However you only need to use the hitCallback when you're tracking an internal link. If you have an external link, and therefore target="_blank", your original tab stays open, and the ga tracking event will complete as normal - you don't have to worry about making sure it finishes before loading the new page.

So I think you'd want to change your click handler to be this:

var trackOutboundLink = function(url, isExternal) {
    var params = {};

    if (!isExternal) {
        params.hitCallback = function () {
            document.location = url;
        }
    }
    ga('send', 'event', 'outbound', 'click', url, params);

    return isExternal;
}

And when you attach this as the click handler

onclick="return trackOutboundLink(urlGoesHere, isExternalGoesHere)"

More concrete examples:

<a href="/" onclick="return trackOutboundLink('/', false)">An internal link</a>
<a href="http://www.example.com/" onclick="return trackOutboundLink('http://www.example.com', true)">An external link</a>