Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Google Analytics Tag Manager to track off site links

I noticed that Google has released their Tag Manager application making it really easy to make changes to your tags and tracking options. How can I use this tool to track off site links?

like image 589
aaron Avatar asked Oct 27 '25 06:10

aaron


1 Answers

Google Tag Manager (GTM) is not a tracking tool, so the short and unhelpful answer is that you can't. However you can deploy Google Analytics via GTM, which I guess is what you mean. I have to say, though, that tracking offsite links turned out a little less straightforward than I expected it to be.

Usually you track external links by virtual pageviews (or events). The usual way in GTM would be to push a variable to the data layer on the click event of the link and then fire a GA tag with a virtual pageview based on a rule based on that event. This failed completely for me when I tested it, presumably because the new page had loaded before the GA tag could fire. So I resorted to a not very elegant workaround:

First I created a standard Google Analytics Tag (tracking type pageview) to make sure the GA code was included in the site. Then I created a custom HMTL Tag with a bit of Javascript (this is assuming you use jQuery in your page):

<script>
$('a').click(function() {
    var p =  $(this).attr('href');  
    if (p.search(/.+YOUDOMAIN/) == -1){         
        _gaq.push(['_trackPageview', "external://" + p]);    // mark links as external in the GA interface
    } 
});
</script>

For all links that do not contain YOURDOMAIN a click event with a pageview is attached to the link. To make sure the all the links are tagged with the click event you set a rule in the tag manager to make sure the script is executed only after the page has loaded you set event based rule in the tag manager where the event is equal to gtm.load (gtm's equivalent of jQuerys domReady).

This works (at least it did in my tests), but since it does not use GTMs intermediary dataLayer it looks rather like a hack to me. If anybody can suggest a proper solution I'd be grateful.

like image 57
Eike Pierstorff Avatar answered Oct 29 '25 05:10

Eike Pierstorff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!