How to correctly check for Do Not Track with JavaScript
Corbin Davenport
May 29
Every modern browser has a Do Not Track setting, which tells sites whether the user wants to be tracked or not. Many sites don't respect this setting, but it's there regardless.
However, checking the value of this setting is far more complicated than it needs to be. Major browsers are split on whether it should be navigator.doNotTrack or window.doNotTrack, and the value can either be a string, a boolean, or undefined. Here's how it boils down:
- Chrome, Opera, and other Blink-based browsers use
navigator.doNotTrack, with values of either1for true or0for false. - Firefox also uses
navigator.doNotTrackwith the same values, but older versions use a different syntax. Prior to v32, Firefox would reportyes,no, orunspecified(more info). - Safari 7.1.3 and later use
window.doNotTrack, while older versions usenavigator.doNotTrack. - Microsoft Edge and Internet Explorer 11 use
window.doNotTrack, and reports1when enabled and 'unspecified' (Edge) or 'null' (IE11) when disabled. - Internet Explorer 10 and older use
navigator.msDoNotTrack, which return '1' or '0'. - On all versions of Internet Explorer, you can also check
window.external.msTrackingProtectionEnabled(), which returns eithertrueorfalse. This was removed in MS Edge.
Suffice to say, the implementation of DND across browsers is pretty inconsistent. But with all those different methods in mind, it's not too difficult to create a fool-proof and universal DNT check:
if (window.doNotTrack || navigator.doNotTrack || navigator.msDoNotTrack || 'msTrackingProtectionEnabled' in window.external) {
// The browser supports Do Not Track!
if (window.doNotTrack == "1" || navigator.doNotTrack == "yes" || navigator.doNotTrack == "1" || navigator.msDoNotTrack == "1" || window.external.msTrackingProtectionEnabled()) {
// Do Not Track is enabled!
} else {
// Do Not Track is disabled!
}
} else {
// Do Not Track is not supported
}
The above code works on every major browser, including Internet Explorer all the way back to IE6 (and possibly earlier, I can't tell when the msTrackingProtectionEnabled function was implemented). You can try a demo here.
Hopefully this helps anyone else running into this problem!
This post is also available on my blog.
Why you should already be using CSS Grid
How to learn to create Progressive Web Apps?
JavaScript Quiz
Equivalents in Python and JavaScript. Part 1
The day I almost made a library on a bakery
Animating Sprite Sheets With JavaScript
How Computers Work?
Did you know CSS has over 400 unique properties

55
2

Well that's a pain all round! Thanks for breaking down all the possibilities. 👍