Search code examples
ruby-on-railsgoogle-tag-managerturbolinks

Unable to effectively use Google Tag Manager with Turbolinks


I'm using Google Tag Manager with a Rails 4.2 app with turbolinks. I'm completely stumped and am completely unable to use Google Tag Manager effectively with turbolinks.

Google tag manager seems to repeatedly sense new page loads (the <body> tag getting replaced) as new installations of google tag manager. When I look at my Google tag assistant recordings I just see an endless sea of Green Tags for Google Tag Manager.

Anyone have any leads on resources where I can figure out how to use it effectively?

I've looked at Googletagmanager with Turbolinks which seems to be slightly dated, but also doesn't solve my problem of errant installations.


Solution

  • Replacing the tag will may all kinds of side effects (as you now realize, one being that the code is re-initialized and fires gtm.js events), so I suggest you drop the noscript part and move the rest to the head - I don't really know turbolinks (or RoR), but according to this article turbolinks will not reload the head.

    Unfortunately there still might be side effects in an SPA since all items pushed to the dataLayer will just stay there. You might want to consider reseting the dataLayer when you load new content:

    window.google_tag_manager[{{Container ID}}].dataLayer.reset();
    

    Where {{Container ID}} is (obviously) the GTM-XXX id for your container. Don't just over the dataLayer variable with an uninitialized array (dataLayer = []) since GTM adds some methods to the dataLayer variable that will get lost if you overwrite it, and your GTM instance will stop to work.