Detect "Do Not Track" with JavaScript

Posted on

It is recommend that we detect DNT (Do Not Track) according to the HTTP header. Howerver, if you insist on detecting DNT with JavaScript, there does be a compatible but experimental way.

The codes are following:

var DNT = 'unspecified'; //default
if(typeof navigator.doNotTrack != 'undefined'){
    DNT = navigator.doNotTrack;
}else if(typeof window.doNotTrack != 'undefined'){
    DNT = window.doNotTrack;
}else if(typeof navigator.msDoNotTrack != 'undefined'){
    DNT = navigator.msDoNotTrack;
}  // DNT can be null, 'unspecified', '1', '0' 'yes' or 'no'
if(DNT == 'yes'){
    DNT = '1'; // Do not track
}else if(DNT == 'no'){
    DNT = '0'; // Please track

if(DNT != '1'){
    // DNT disabled, do something...

Or, if you do not consider "Please track" (DNT=0), you can just use the codes:

if(!!navigator.doNotTrack && navigator.doNotTrack!='unspecified' || !!window.doNotTrack || !!navigator.msDoNotTrack){
    // DNT enabled
    // DNT disabled, do something...


2018-7-20 P.S.Another form of codes added.

1 Comment

  1. Baizid Baizid

    You are always putting great stuff. I really appreciate that and follow your blogs. Thanks for updating such wonderful information.


Leave a comment»