如何检测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;
}
当前回答
你可以很容易地使用索引的Chrome过滤Chrome:
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') > -1) {
alert("1") // Chrome
} else {
alert("2") // 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));
}
为上面的答案修改正则表达式
var isSafari = /^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent);
低温-铬 fxios - Firefox
只有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>
这个独特的“问题”是100%的标志,浏览器是Safari(信不信由你)。
if (Object.getOwnPropertyDescriptor(Document.prototype, 'cookie').descriptor === false) {
console.log('Hello Safari!');
}
这意味着cookie对象描述符在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
}