Skip to content

Instantly share code, notes, and snippets.

@hannesl
Created April 4, 2018 09:54
Show Gist options
  • Save hannesl/97af3132cc0d1efc72e86e872438f5b4 to your computer and use it in GitHub Desktop.
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
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');
});
}
@hannesl
Copy link
Author

hannesl commented Apr 4, 2018

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 with datalayer.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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment