John Paul Hayes
John Paul Hayes

Reputation: 798

How can you ignore google tracking when "do not track" flag is set by browser?

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?

Upvotes: 0

Views: 884

Answers (1)

str
str

Reputation: 44979

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

Upvotes: 5

Related Questions