loading...

How to correctly check for Do Not Track with JavaScript

corbindavenport profile image Corbin Davenport ・2 min read

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:

  1. Chrome, Opera, and other Blink-based browsers use navigator.doNotTrack, with values of either 1 for true or 0 for false.
  2. Firefox also uses navigator.doNotTrack with the same values, but older versions use a different syntax. Prior to v32, Firefox would report yes, no, or unspecified (more info).
  3. Safari 7.1.3 and later use window.doNotTrack, while older versions use navigator.doNotTrack.
  4. Microsoft Edge and Internet Explorer 11 use window.doNotTrack, and reports 1 when enabled and 'unspecified' (Edge) or 'null' (IE11) when disabled.
  5. Internet Explorer 10 and older use navigator.msDoNotTrack, which return '1' or '0'.
  6. On all versions of Internet Explorer, you can also check window.external.msTrackingProtectionEnabled(), which returns either true or false. 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.

Discussion

markdown guide
 

This does not work if DNT is enabled but the user explicitly excluded a site from being "not tracked" (in Firefox for instance by clicking the shield icon and setting "Content Blocking" to off). Any idea how to retrieve this specific setting?

 

Well that's a pain all round! Thanks for breaking down all the possibilities. πŸ‘