如何检测Safari浏览器使用JavaScript?我尝试了下面的代码,它不仅检测Safari浏览器,而且还检测Chrome浏览器。
function IsSafari() {
var is_safari = navigator.userAgent.toLowerCase().indexOf('safari/') > -1;
return is_safari;
}
如何检测Safari浏览器使用JavaScript?我尝试了下面的代码,它不仅检测Safari浏览器,而且还检测Chrome浏览器。
function IsSafari() {
var is_safari = navigator.userAgent.toLowerCase().indexOf('safari/') > -1;
return is_safari;
}
当前回答
此代码仅用于检测safari浏览器
if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0)
{
alert("Browser is Safari");
}
其他回答
因为chrome和safari的userAgent几乎是相同的,所以可以更容易地查看浏览器的供应商
Safari
navigator.vendor == "Apple Computer, Inc."
铬
navigator.vendor == "Google Inc."
FireFox(为什么是空的?)
navigator.vendor == ""
IE(为什么没有定义?)
navigator.vendor == undefined
阅读了许多答案和帖子,并确定了最准确的解决方案。在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
}
基于@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过滤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')
编辑:不再工作