1

I want to track users clicking links to external sites. I'm happy to use the asynchronous version of GA as this allows (in most browsers) the page to continue loading instead of halting at the script tag and waiting for google-analytics.com/ga.js to download and execute.

Google recommends this function:

<script type="text/javascript">
function recordOutboundLink(link, category, action) {
  try {
    var myTracker=_gat._getTrackerByName();
    _gaq.push(['myTracker._trackEvent', ' + category + ', ' + action + ']);
    setTimeout('document.location = "' + link.href + '"', 100)
  }catch(err){}
}
</script>

<a href="http://www.example.com" onClick="recordOutboundLink(this, 'Outbound Links', 'example.com');return false;">

The problems with this solution:

  • It could take 10ms, it could take 300ms for the event to be tracked, but it'll change the page after 100ms no matter what happens. And if the tracking is too slow the page will change before it's been tracked.
  • document.location = means the original link is ignored and therefore target=_blank does not open new tabs/windows.
Tom Viner
  • 6,655
  • 7
  • 39
  • 40
  • See also: http://stackoverflow.com/questions/10260818/google-analytics-record-outbound-links-open-new-window/12317986#12317986 – Jeff Sep 10 '12 at 20:18

1 Answers1

1

Possible solutions:

  • Busy wait (do {curDate=new Date();} while(curDate-date<millis)) for 100ms while the tracking has a chance to send it's request off then return true. Bad because busy waiting consumes all CPU available.
  • Use window.open so that new tabs/windows can be opened, which leads me to my current favourite:

  • In the click handler use $(this).attr("target", "_blank"); and then just return true after pushing the tracking command onto _gaq.

This works because open a new tab leaves the current one to finish executing the tracking call.

$(document).ready(function(){
  var localserver = document.location.hostname;
  // unfortunately misses if any uppercase used in link scheme
  $("a[href^=http://],a[href^=https://]") 
    .not("a[href^=http://"+localserver+"]")
    .not("a[href^=http://www."+localserver+"]")
    .click(function(e){
        $(this).attr("target", "_blank");
        _gaq.push(['_trackEvent', 
                   'Outgoing Click',
                   $(this).attr("href"),
                   $(this).text()
                 ]);
        return true;
    });
});

With the one small downside of always opening a new tab for external links, I can't see any other problems.

Tom Viner
  • 6,655
  • 7
  • 39
  • 40