Search code examples
google-analyticsgtag.js

Prevent gtag / global site tag from tracking initial page load


We have a single page application using Gtag (Global Site Tag), and we manage the tracking of pages manually to provide the correct page names that we want to track. So we call

gtag('config', gaPropertyId, gtagPageConfig)

every time there is a route change.

This means that we don't want gtag to track pages for us automatically, as we are currently tracking all initial pages twice. The first is when gtag is automatically firing the tracking of the page by sending the browser title and the URL, and the second time is when we trigger the page view from our code, to provide the title for that page that we want to have see in Google Analytics.

After a lot of research and debugging, I've narrowed it down to the settings screen, where "Page loads" is checked, and can't be disabled, see this image:

Unable to prevent page loads

We load our script like this:

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-xxx-1"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'G-xxx', { 'send_page_view': false });
</script>

When I remove the line gtag('js', new Date());, it doesn't track the page anymore, but this will probably result in some unwanted behaviour.

Is there a way for us to prevent the initial page load tracking? I've searched everywhere, but can't find the solution.


Solution

  • Simply you should NOT include those fields on pages you don't want to send any data to Google:

    gtag('js', new Date());
    gtag('config', 'G-xxx');
    

    Your snippet should look like this without date and config:

    <script async src="https://www.googletagmanager.com/gtag/js?id=G-xxx"></script>
    <script>window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}
    

    Sending data

    SPA (i.e. Vue, React, etc)

    If you are using SPA (i.e. Vue, React), you can run gtag function after route updated:

    gtag('js', new Date());
    gtag('config', 'G-xxx', { page: path: route.path, page_title: route.meta.title })
    

    PHP

    You can show up date and config conditionally:

    <?php if (/* suits my needs*/): ?>
      gtag('js', new Date());
      gtag('config', 'G-xxx');
    <?php endif; ?>