1

I do not see where my error is, If there is any

<!DOCTYPE html> <html> <head>
        <script type="text/javascript">
            //http://stackoverflow.com/questions/10251149/using-javascript-to-detect-google-chrome-to-switch-css
            //provera brosera
            function check_chrome_ua() {
                var ua = navigator.userAgent.toLowerCase();
                var is_chrome = /chrome/.test(ua);
                alert("func check_chrome_ua() " + is_chrome);
                return is_chrome;
            }
            //promena nadpisa
            function check() {
                //alert("check1");

                var check = check_chrome_ua();
                alert("var check " + check + "; func check_chrome_ua() " + check_chrome_ua());

                if (check == "false") {
                    alert("change text");
                    document.getElementById("opomena").style.color = "red";
                    document.getElementById("opomena").innerHTML = 'Warning you are not using Google Chrome';
                }
            }
        </script>
        </head>
        <body onmousemove="check()">
    <div id="opomena">Thank you for using Google Chrome.</div>

</body>
 </html>

Popups on Google Chrome popup says true, on Firefox says false popup "change text" does not display in Firefox tho var check is false.

Thank you in advance for advice

Ibu
  • 42,752
  • 13
  • 76
  • 103
nkvnkv
  • 914
  • 2
  • 12
  • 25

2 Answers2

4

Change

if (check == "false") {

to

if (!check) {

or

if (check == false) {

if you really want to check for the boolean value, false.

The regexp, test method which you call at /chrome/.test(ua) returns a boolean, but check == "false" is comparing that boolean to a string. The two are not equal.

In JavaScript, == is permissive when it comes to comparing strings to objects, but not as permissive as Perl's eq operator.

  • 0 == false
  • false == false
  • "false" == [false]
  • false != "false"
  • 0 != "false"

It's a good habit to try and use !== and === which are well-defined operators to compare primitive values.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
1

You have to check for boolean value false, not "false" (it's a string).

Only if (!check) would be enough (or more verbose version if (check == false) ).

User
  • 31,811
  • 40
  • 131
  • 232