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.
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:
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With