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

function IsSafari() {

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

}

当前回答

这个独特的“问题”是100%的标志,浏览器是Safari(信不信由你)。

if (Object.getOwnPropertyDescriptor(Document.prototype, 'cookie').descriptor === false) {
   console.log('Hello Safari!');
}

这意味着cookie对象描述符在Safari上设置为假,而在其他所有项目上设置为真,这实际上让我在其他项目上头疼。编码快乐!

其他回答

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

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

基于@SudarP的回答。

在2021年Q3,这个解决方案将失败在Firefox (Uncaught TypeError: navigator.vendor.match(…)是null)和Chrome (Uncaught TypeError:不能读取null属性(读取'length'));

所以这里有一个固定且简短的解决方案:

function isSafari() {
  return (navigator.vendor.match(/apple/i) || "").length > 0
}

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

Safari

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

navigator.vendor ==  "Google Inc."

FireFox(为什么是空的?)

navigator.vendor ==  ""

IE(为什么没有定义?)

navigator.vendor ==  undefined

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

var ua = navigator.userAgent.toLowerCase(); 
if (ua.indexOf('safari') != -1) { 
  if (ua.indexOf('chrome') > -1) {
    alert("1") // Chrome
  } else {
    alert("2") // 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>