Created
April 4, 2018 09:54
-
-
Save hannesl/97af3132cc0d1efc72e86e872438f5b4 to your computer and use it in GitHub Desktop.
Trigger page load events in Google Analytics with JavaScript when using Google Tag Manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (typeof ga === "function") { | |
ga.getAll().forEach((tracker) => { | |
tracker.set('page', '/my/path'); // <- change here | |
tracker.send('pageview'); | |
}); | |
} | |
// ES5 version for backward compatibility | |
if (typeof ga === "function") { | |
ga.getAll().forEach(function (tracker) { | |
tracker.set('page', '/my/path'); // <- change here | |
tracker.send('pageview'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Google Tag Manager is both amazing and awful. The official solution for sending virtual page loads is to set up a custom event in the Tag Manager UI with a
page
variable, and then trigger this event withdatalayer.push()
. I don't like the added complexity of setting up a custom event if I don't have to. There's also the risk that it could get broken at any time by someone (me) who messes around in the Tag Manager UI.This solution is basically the same as when using the good old
analytics.js
. What you need to do differently with Tag Manager is that you have to get the tracker object dynamically, as explained by Simo Ahava in this thread.