In a recent project, we wanted to use Google Tag Manager (GTM) along with Rails. The trick, however, is that most Ruby on Rails projects these days use Turbolinks. This post shows how to get up and running quickly.
The Problem w/ GTM and Turbolinks
In the case of GTM, the first time you load a page of your app, the “All Pages” trigger will fire. Subsequent page visits will not trigger on this, so you won’t get the same sort of script loading behavior you may expect.
There are already some articles online and on stackoverflow on how to resolve this issue, however, they seem to have been written some time ago and don’t account for the current version of Google Tag Manager. Here are the current steps you should take to get up and running.
Add GTM and Custom Trigger to Your Site
We added the following code right before the end of the head section. The first section of code notifies GTM when turbolinks changes the page. The second section of code is just the vanilla code that GTM provides to you. Be sure to replace the latter chunk of code with the unique code that Google Tag Manager provides you.
<!-- Google Tag Manager trigger for Turbolinks -->
var url = window.location.href;
<!-- End Google Tag Manager trigger for Turbolinks -->
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=[YOUR ID]"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s),
<!-- End Google Tag Manager -->
Wiring Your Tags To Fire
Once you’ve completed the above step, you need to create a Trigger object in GTM. You’ll associate this object with tags in GTM, allowing you to determine which tags “fire” when Turbolinks changes the page.
Follow these steps:
- In GTM, click “Triggers”. Click “New”.
- Select “Custom Event”.
- For “Event name”, enter “pageView”.
- Click “Create Trigger”.
To associate a tag with your new trigger:
- Create a new tag or edit an existing tag.
- Under “Fire On”, click “More”.
- Select the trigger you just created and click “Save”.
- Click “Save Tag”.
- Be sure to click “Publish” once you’ve made all of your changes so that the changes go live.
That’s it. You should be go!