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.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With