8

I'm working on a javascript advertising engine, and I would like for it to respect Firefox DNT header.

Is there any way javascript can check if the user has set DNT to on or off in firefox (or has set no preferences) without getting help from the server?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Arsen Zahray
  • 24,367
  • 48
  • 131
  • 224

1 Answers1

12

I think you're looking for navigator.doNotTrack:

console.log(window.navigator.doNotTrack); 
// prints "yes" if DNT is enabled; otherwise this is "unspecified" in Firefox

MDN explains that in Firefox:

When the do-not-track header sends "1", navigator.doNotTrack is "yes". When the header is unset, navigator.doNotTrack is "unspecified". When the header sends "0" (currently unsupported in Firefox), navigator.doNotTrack is "no".

In other browsers:

IE9, Opera 12, and Safari 5.1 are based on an earlier version of this specification where navigator.doNotTrack is the value sent for the do-not-track header.

IE9 uses a vendor prefix, i.e., navigator.msDoNotTrack

So, you might detect DNT in general by doing:

var isDNT = navigator.doNotTrack == "yes" || navigator.doNotTrack == "1" || 
              navigator.msDoNotTrack == "1";
Community
  • 1
  • 1
apsillers
  • 112,806
  • 17
  • 235
  • 239
  • 1
    Actually, I got FF to send `DNT: 0` by checking "tell the websites that I want to be tracked". FF supports this – Arsen Zahray Jun 05 '13 at 18:55
  • @ArsenZahray Interesting! Looks like the last time the MDN article was updated was over a year ago, so a lot may have changed since then. Even so, since you're only looking for positive DNT results, my final code snippet *should* work regardless (though I haven't tested it). – apsillers Jun 05 '13 at 18:59
  • 1
    @ArsenZahray I just did a quick test in FF21, and it looks like "Tell the websites that I want to be tracked" and "Tell the websites that I do *not* want to be tracked" both produce a "`yes`" value, while leaving it set to the default "send nothing" produces "`undefined`". I think that in time they'll correct it and "please *do* track me" will eventually get turned into a "`no`". In the meantime, it's probably not so bad to treat all "`yes`" values as meaning "do *not* track me", since the people who opt into tracking will likely be quite rare. – apsillers Jun 05 '13 at 19:08
  • Just a quick update: [doNotTrack is on the window object as of IE11](http://stackoverflow.com/a/24155355/1647538) and Safari 6.1.1+, and may be moved as such for Firefox and Blink as well, in the future. – hexalys Jun 11 '14 at 22:51
  • @apsillers This is [fixed](https://bugzilla.mozilla.org/show_bug.cgi?id=887703) for the upcoming Firefox 32+. Personally on the basis of this bug, I will treat DNT as `undefined/null`, since the feature is deemed an unreliable setting from Firefox 21-32. – hexalys Jun 11 '14 at 23:01