Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Analytics: how to track outbound links that open in a new tab?

I have a number of outbound links on a website which I'm hoping to track with Google Analytics (analytics.js).

Google's docs on outbound link tracking are clear and the implementation they suggest works for me. The problem is with links that open in a new tab / window. Google suggests that the links be opened via a callback function which updates the document.location once the tracking event has been sent to GA. But this obviously won't open links in a new tab. And, crucially, using window.open instead seems to fall victim to popup blockers.

This is Google's suggested implementation:

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

I can simply omit the callback function and let the browser open the new tab but if I do that, Google says there's a chance the event won't get registered - and my tracking will be inaccurate.

like image 265
Alex G Avatar asked Jan 10 '23 21:01

Alex G


1 Answers

If you are tracking outbound links on click and your links are to open up in a new window or tab, you don't have to worry about a callback. The page will track the event just fine. The issue comes from links in the same frame, since the page with the click tracking is being torn down at the same time the event for the click is being sent. So, for links with targets in new windows/tabs, don't worry as your normal click event will work fine.

If you need to track outbound links but are concerned about links opening in the current tab/window, one solution is to have a server-side redirect script that does the Google Analytics tracking. It works a bit like this:

  • On mousedown, the href attribute of the link is replaced via JavaScript. From http://example.com to /yourTrackingScript?gaCategory=Something&gaEvent=Click&gaLabel=SomeLink&url=http%3A%2F%2Fexample.com. It's important that this happens on mousedown so that if someone right-clicks your link to open in a new tab/window, the server-side tracking script is still inserted. Google uses this method on their search results page.
  • /yourTrackingScript fires off your event from the server-side to Google Analytics using the measurement protocol.
  • /yourTrackingScript responds with a 302 redirect to whatever URL was passed in the query string.
  • The user is redirected to the final destination, and this all typically happens fast enought that they don't even notice.
like image 70
Brad Avatar answered Jan 15 '23 19:01

Brad