Quoted from https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
When your application loads content dynamically and updates the URL in the address bar, the data stored on your tracker should be updated as well.
ga('set', 'page', '/new-page.html');
How can I run this if I am using Google Tag Manager with Google Analytics?
Below is snippet of how I track for pageview whenever route change on React router using higher order component
componentDidMount() {
const { history } = this.props;
this.history = history.listen(location => {
if (history.action === 'PUSH') {
// location change
if (window && window.dataLayer) {
const dataLayer = window.dataLayer || [];
const { pathname, search } = location;
// how to achieve this with Google Tag Manager?
// ga.set('page', `${pathname}${search}`);
setTimeout(() => {
dataLayer.push({
event: 'Pageview',
});
}, 1000);
}
}
});
}
If you're using GTM, then I can recommend two options.
Option 1, if your app actually updates the URL as routing changes:
Create a custom event trigger to track that Pageview
event you've pushed to the data layer.
Go into "Variables" and make sure you have "Page Path" selected.
Create a new GA Tag and make sure you check "Enable overriding settings in this tag" and then on the bottom there is drop down for "More Settings" and you'll see "Fields to Set", click on "Add Field" and you can add "page" and set the value to the {{Page Path}}. Then add in the trigger created in step 1
Save and run and you should be sending pageview data to GA via this event. The path will be whatever that's in the browser's url bar.
If you want an even more customized path, then you can modify your code to the following, we added "page-path" variable to the data layer.
componentDidMount() {
const { history } = this.props;
this.history = history.listen(location => {
if (history.action === 'PUSH') {
// location change
if (window && window.dataLayer) {
const dataLayer = window.dataLayer || [];
const { pathname, search } = location;
// how to achieve this with Google Tag Manager?
// ga.set('page', `${pathname}${search}`);
setTimeout(() => {
dataLayer.push({
page-path: ${pathname}${search},
event: 'Pageview'
});
}, 1000);
}
}
});
}
Then you need to setup a new datalayer variable to capture this in GTM:
Then go back to the GA tag created before and modify the "page" field value to this new variable: