1

I'm trying to detect the "Do not track" setting on browsers... the origionla working code is:

if(navigator.doNotTrack == "yes" || navigator.doNotTrack == "1" || navigator.msDoNotTrack == "1"){
    alert("true");
}else{
    alert("false");
}

I'm trying to re-write it slightly and I'm wondering how to use a conditional within a variable declaration? I've come up with a not-working snippet that I was wondering if someone could help me with?

var DNT     = navigator.doNotTrack,
    msDNT   = navigator.msDoNotTrack,
    DNTtrue = "yes" || "1";

if(DNT === DNTtrue || msDNT === DNTtrue){
    alert("true");
}else{
    alert("false");
}
5
  • this DNTtrue = "yes" || "1"; results to true due to javascript lose typing. which means this DNT === DNTtrue is equivalent to DNT === true Commented Jun 24, 2013 at 11:25
  • 3
    that's not true, "yes" || "1" results to "yes" Commented Jun 24, 2013 at 11:25
  • OK so how do I make it equal to "yes" or "1"?? Commented Jun 24, 2013 at 11:27
  • what's wrong with the 1st condition? Commented Jun 24, 2013 at 11:30
  • Nothing wrong with it really, just like to re-write things to help improve my JS Commented Jun 24, 2013 at 11:32

3 Answers 3

3

You can't to it like this. The expression "yes" || "1" is evaluated at the moment it is encountered. So you end up comparing DNT and msDNT to "yes". There is no way to tell JS to evaluate an expression later instead. In even then, DNT === "yes" || "1" or DNT === ("yes" || "1") would not yield desired results either.

Here is an alternative solution, which simply tests whether the value of DNT or msDNT exists are property in an object:

var DNTtrue = {"yes": true, "1": true};

if (DNTtrue[DNT] || DNTtrue[msDNT]) {
    // ...    
}

If DNT or msDNT have a different value than "yes" and "1", then DNTtrue[...] tries to access a non-existing property which will result in undefined (a falsy value).

Sign up to request clarification or add additional context in comments.

2 Comments

Legend!! could you explain the inner working a little more? Will accept after 3 mins
Thanks, understand much better now, will definitely use this technique in the future
1

In modern browsers you could use an array and the indexOf() method:

DNTtrue = ["yes", "1"];

if(DNTtrue.indexOf(DNT) > -1 || DNTtrue.indexOf(msDNT) > -1){
    alert("true");
}else{
    alert("false");
}

Comments

0

Try DNT.value inside if statement Make DNTtrue=true not to yes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.