0

What is the best practice for honouring, via Javascript, the DNT flag set in modern browsers?

Ultimately, I want to disable the likes of Google Analytics, Facebook pixel and other bespoke tracking codes if it is set.

Are there any gotchas to be aware of?

Ivar
  • 6,138
  • 12
  • 49
  • 61
John Paul Hayes
  • 778
  • 6
  • 13

1 Answers1

5

You can read the flag using navigator.doNotTrack and conditionally load those trackers.

For Google Analytics, you could use the following code:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script>
    if (navigator.doNotTrack !== '1') {
        (function () {
            var ga = document.createElement('script');
            ga.type = 'text/javascript';
            ga.async = true;
            ga.src = 'https://www.googletagmanager.com/gtag/js?id=UA-ADD-YOUR-ID';
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(ga, s);
        })();
        window.dataLayer = window.dataLayer || [];
        function gtag() {
            dataLayer.push(arguments);
        }
        gtag('js', new Date());
        gtag('config', 'UA-ADD-YOUR-ID');
    }
</script>

(Also replace ADD-YOUR-ID with your actual ID.)

Resources

str
  • 42,689
  • 17
  • 109
  • 127