我的浏览器检测代码是这样的
navigator.sayswho = (function () {
var ua = navigator.userAgent;
var tem;
var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=/))/?s*(d+)/i) || [];
if (/trident/i.test(M[1])) {
tem = /brv[ :]+(d+)/g.exec(ua) || [];
return 'IE ' + (tem[1] || '');
}
if (M[1] === 'Chrome') {
tem = ua.match(/b(OPR|Edge)/(d+)/);
if (tem != null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
if ((tem = ua.match(/version/(d+)/i)) != null) M.splice(1, 1, tem[1]);
return M.join(' ');
})();
alert(navigator.sayswho); // outputs: `Chrome 62`
});
所有看起来都很好,但在边缘,这段代码返回浏览器为"Chrome"。我该如何解决这个问题?
通常我把边缘检查放在顶部来传递这个。当你试着去看
userAgent in chrome:Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
userAgent in Edge:Mozilla/5.0 (Windows NT 10.0;Win64;x64;ServiceUI 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19041
即使在Edge中,它也包含在Edge之前的铬。使用下面的代码来检查,通常在chrome之前检查Edge。
function fnBrowserDetect(){
let userAgent = navigator.userAgent;
let browserName;
if(userAgent.match(/edg/i)){
browserName = "edge";
}
else if(userAgent.match(/chrome|chromium|crios/i)){
browserName = "chrome";
}else if(userAgent.match(/firefox|fxios/i)){
browserName = "firefox";
} else if(userAgent.match(/safari/i)){
browserName = "safari";
}else if(userAgent.match(/opr//i)){
browserName = "opera";
}else{
browserName="No browser detection";
}
return "You are using "+ browserName +" browser";
}
基本上,您目前正在使用遗留方法来检测用户客户机。新标准建议使用navigator.userAgentData.brands
来检测实际的浏览器客户端名称,无论是chrome还是edge。你可以在这里看到edge。您也可以查看mdn的官方文档。