Google tag manager not sending analytics request after route changes

Viewed 4363

I am trying to implement google tag manager in react application. It works on page reload, but when I move between my application through routes, it does not register a page view in google analytics.

I have tried react-gtm-module, but it is also working on reload and not on route changes.

index.html added below code in head tag.

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXX');</script>
<!-- End Google Tag Manager -->

added below code in body tag.

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

and inside my components componentDidMount, I am pushing new pageView in dataLayer

dataLayer.push({
    event: 'Pageview',
    pagePath: 'page-path-here',
    pageTitle: 'page-title-here',
});

I have created pagePath and pageTitle dataLayer variables and a assigned them to Google analytics tag.I have also created a custom triggerPageView and added it to firing triggers in Google analytics tag.

Data layer variables data layer variables list

Custom triggers custom trigger

Assignment of data layer variables to Analytics tag google analytics data layer variables

Can anyone please point me in correct direction?

Edit: Detail Data layer variable view google analytics data layer variables detai

First load (reload) google analytics data layer variables detai

Route change google analytics data layer variables detai

2 Answers

The code you have written in index.html only runs once when the page is loaded if you want to register an event on page change you need to trigger the same on the routes you want to trigger, you can access the dataLayer variable from window

I changed my componentDidMount code to

window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
    event: 'Pageview',
    pagePath: 'page-path-here',
    pageTitle: 'page-title-here',
});

Datalayer push

Now I can see page views in Google Analytics on route changes.

Related