Reputation: 798
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
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.)
Upvotes: 5