Search code examples
google-analyticsgoogle-analytics-api

Remove all traffic for a specific user agent


Is there a way to exclude, from all properties and all views of Google Analytics, the visitors with a specific user agent?

Note: it's not for spam/bot prevention (I already checked the feature Admin > View settings > Bot filtering > Exclude all hits from known bots and spiders), it's to remove a part of own traffic. I can't use IP filtering because my IP changes all the time, and I use many devices (mobile/desktop/laptop). I also can't use cookies, because often I want to test my website as a random non-logged user. I didn't find anything even after exploring deeply the Analytics UI. Maybe this requires API ?


Solution

  • (Google Tag Manager seemed a bit labyrinthic for me.)

    I finally did this:

    • Use Custom UserAgent String extension (available for FF and Chrome) and set UserAgent to NoTracking (you can do it specifically for certain websites, i.e. your websites only, see options).

    • Add this in the PHP page, in the Analytics Javascript part:

      <?php  if ($_SERVER ['HTTP_USER_AGENT'] === 'NoTracking') echo 'if (false)'; ?>
      

      It looks like this:

      <script>
      <?php  if ($_SERVER ['HTTP_USER_AGENT'] === 'MyselfXYZ12') echo 'if (false)'; ?>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)}) window,document,'script','https://www.google-analytics.com/analytics.js','ga');
      ga('create', 'UA-xxxxxxx-x', 'auto');
      ga('send', 'pageview');
      <script>
      

      This will have the effect of disabling the creation of ga object for your traffic only.

    NB: I first thought about disabling GA code for my own traffic via Javascript with if (navigator.userAgent == 'NoTracking') but it seems that the UserAgent change thanks to the extension "Custom UserAgent String" has effect only after the page is rendered, which is too late.