如何检测Safari浏览器使用JavaScript?我尝试了下面的代码,它不仅检测Safari浏览器,而且还检测Chrome浏览器。

function IsSafari() {

  var is_safari = navigator.userAgent.toLowerCase().indexOf('safari/') > -1;
  return is_safari;

}

当前回答

你可以很容易地使用索引的Chrome过滤Chrome:

var ua = navigator.userAgent.toLowerCase(); 
if (ua.indexOf('safari') != -1) { 
  if (ua.indexOf('chrome') > -1) {
    alert("1") // Chrome
  } else {
    alert("2") // Safari
  }
}

其他回答

也许这样行得通:

Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor')

编辑:不再工作

只有Safari浏览器没有Chrome浏览器:

在尝试了其他代码之后,我没有发现任何适用于新版本和旧版本Safari的代码。

最后,我做了这段代码,对我来说工作得很好:

var ua = navigator.userAgent.toLowerCase(); var isSafari = false; try { isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification); } catch(err) {} isSafari = (isSafari || ((ua.indexOf('safari') != -1)&& (!(ua.indexOf('chrome')!= -1) && (ua.indexOf('version/')!= -1)))); //test if (isSafari) { //Code for Safari Browser (Desktop and Mobile) document.getElementById('idbody').innerHTML = "This is Safari!"; } else { document.getElementById('idbody').innerHTML = "Not is Safari!"; } <body id="idbody"> </body>

为上面的答案修改正则表达式

var isSafari = /^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent);

低温-铬 fxios - Firefox

此代码仅用于检测safari浏览器

if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) 
{
   alert("Browser is Safari");          
}

我用这个

function getBrowserName() {
    var name = "Unknown";
    if(navigator.userAgent.indexOf("MSIE")!=-1){
        name = "MSIE";
    }
    else if(navigator.userAgent.indexOf("Firefox")!=-1){
        name = "Firefox";
    }
    else if(navigator.userAgent.indexOf("Opera")!=-1){
        name = "Opera";
    }
    else if(navigator.userAgent.indexOf("Chrome") != -1){
        name = "Chrome";
    }
    else if(navigator.userAgent.indexOf("Safari")!=-1){
        name = "Safari";
    }
    return name;   
}

if( getBrowserName() == "Safari" ){
    alert("You are using Safari");
}else{
    alert("You are surfing on " + getBrowserName(name));
}