7

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?

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
Charles Ingalls
  • 4,521
  • 5
  • 25
  • 33

6 Answers6

15

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>
alexp
  • 3,587
  • 3
  • 29
  • 35
  • Thanks Alex! The only thing I am wondering: The link will always be an external link. However, sometimes it will open in a new tab and at other times it will open in the same tab (by user choice). Do I need to pass the same URL for "url" and "isExternal" to the trackOutboundLink() function? – Charles Ingalls Nov 14 '14 at 22:52
  • I meant for isExternal to be a boolean for whether the link opens in a new window. You should just set that from PHP the same way you are setting the URL from PHP. The exact implementation would depend on whatever criteria you use to determin external vs. internal links. – alexp Nov 14 '14 at 23:12
  • 'hitCallback': function() { if (target.attr('target') !== '_blank') { window.location.href = url; } } – albertpeiro May 06 '16 at 22:48
5

Just want to support Some Guy In Winnipeg's answer above. Won't let me comment, but his solution works!

Google's suggested code (does not work to open link in new tab) is:

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

:

<a href="http://www.example.com" onclick="trackOutboundLink('http://www.example.com'); return false;">Check out example.com</a>

However, if you change "document.location = url;" to "document.location = href;" and in the link tag, change "return false;" to "return true;" and add "target="_blank", the link will open in a new tab, and track the outbound link.

So, the code that works is:

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

:

<a href="http://www.example.com" onclick="trackOutboundLink('http://www.example.com'); return true;" target="_blank;">Check out example.com</a>
Ted Converse
  • 59
  • 1
  • 1
  • I think the whole point of hitCallback is opening the received link in a new window. so if you use return true along with it, it's more like a redundant step. what return false does it cancelling the navigation, so go() function can do it. – Don Dilanga Oct 09 '17 at 09:52
  • This works perfectly, although I always get a "Uncaught ReferenceError: href is not defined at hitCallback" error in console. – Drowned Nov 30 '18 at 03:05
  • the error "Uncaught ReferenceError: href is not defined at hitCallback" happens – Carlos G. Aug 27 '19 at 17:48
4

This will make all links open in a new window:

    var trackOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){window.open(url);}
   });
}

I just changes document.location = url; to window.open(url); code from https://support.google.com/analytics/answer/1136920

you can also change the function name,and have one for new window links, and one for same window links. That would be change the 1st line to something like:

var trackOutboundNewWindow = function(url) {

And then the link would be

<a href="http://www.example.com" onclick="trackOutboundNewWindow('http://www.example.com'); return false;">Check out example.com</a>
Jon
  • 6,437
  • 8
  • 43
  • 63
1

Found a solution (as of Feb 6 2016)

<script>
var trackOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){document.location = href;}
   });
}
</script>

Then make your link look like this...

<a href="http://www.example.com" onclick="trackOutboundLink('label name'); return true;" target="_blank">text</a>
0

DRY - track all anchor's with a 'tracked' class. Note this code is sensitive to popup blockers. The window.open call needs to be outside the ga call.

/**
* Function that tracks a click on an outbound link in Analytics.
*/
$(function() {
    //only create event tracking if ga has loaded
    ga(function(){
        $("a.tracked").click(function(e) {
            var url = $(this).attr("href");
            var newWindow = ($(this)[0].target || '').toLowerCase() === '_blank';
            if(newWindow) {
                window.open(url, '_blank');
            }
            ga("send", "event", "outbound", "click", url, {
                "hitCallback": function () {
                    if(!newWindow) document.location = url;
                }
            });
            e.preventDefault();
        });
    });
});
jenson-button-event
  • 18,101
  • 11
  • 89
  • 155
-2

this works:

hitCallback': function(){window.open(url);}

Hope, that the event tracking is not affected in any way.

Vinoth Krishnan
  • 2,925
  • 6
  • 29
  • 34
Vincent P.
  • 33
  • 5