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

function IsSafari() {

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

}

当前回答

只有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>

其他回答

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

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

因为chrome和safari的userAgent几乎是相同的,所以可以更容易地查看浏览器的供应商

Safari

navigator.vendor ==  "Apple Computer, Inc."

navigator.vendor ==  "Google Inc."

FireFox(为什么是空的?)

navigator.vendor ==  ""

IE(为什么没有定义?)

navigator.vendor ==  undefined

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

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");          
}

阅读了许多答案和帖子,并确定了最准确的解决方案。在Safari, Chrome, Firefox和Opera(桌面和iOS版本)中进行测试。首先,我们需要检测苹果供应商,然后排除Chrome, Firefox和Opera(用于iOS)。

let isSafari = navigator.vendor.match(/apple/i) &&
             !navigator.userAgent.match(/crios/i) &&
             !navigator.userAgent.match(/fxios/i) &&
             !navigator.userAgent.match(/Opera|OPT\//);

if (isSafari) {
  // Safari browser is used
} else {
  // Other browser is used
}