Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome is detected as Safari with javascript

I am looking for a way to detect Safari with javascript. I know its been covered many times already but probably something got changed and it does not work anymore. At least in my case.

Here is what I do:

<script>

    if(!isSafari()){
      alert('not Safari');
    } else {
      alert('I am Safari');
    }


    function isSafari(){    
      var is_safari = navigator.userAgent.indexOf("Safari") > -1;
      if(is_safari){
        return true;
      }
    }
  </script>

jsbin: http://jsbin.com/ewerof/1

If you run this code in Safari and Chrome you will get the same alert "I am Safari" So how to actually detect Safari only? My Safari version is 4.0.3 just in case if that matters.

like image 224
devjs11 Avatar asked Dec 05 '22 14:12

devjs11


2 Answers

Chrome has both 'Chrome' and 'Safari' inside userAgent string. Safari has only 'Safari'.

So this works:

var is_chrome = navigator.userAgent.indexOf('Chrome') > -1; 
var is_explorer = navigator.userAgent.indexOf('MSIE') > -1; 
var is_firefox = navigator.userAgent.indexOf('Firefox') > -1; 
var is_safari = navigator.userAgent.indexOf("Safari") > -1; 
var is_Opera = navigator.userAgent.indexOf("Presto") > -1; 
if ((is_chrome)&&(is_safari)) {is_safari=false;} 

if (is_safari) alert('Safari');

Or for Safari only, use this :

if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {alert('Its Safari');} 

Credit: Kabamaru

like image 161
mrd Avatar answered Dec 28 '22 11:12

mrd


If you type this in a web developer console using Chrome:

navigator.userAgent

You will get a string, something like:

"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.92 Safari/537.4"

This string contains Safari, so you have to check specifically if the string also contains chrome. You can use a simple one-liner for that:

var is_safari = /^(?!.*chrome).*safari/i.test(navigator.userAgent);
like image 20
David Hellsing Avatar answered Dec 28 '22 09:12

David Hellsing