浏览器类型主要是需要从window对象中的userAgent属性来判断。
如在IE浏览器中这个字段是这样的:
在Edge浏览器中这个字段是这样的:
在Chrome浏览器中这个字段是这样的:
一般我们只需要判断浏览器是不是IE就OK了。
我们可以根据查找userAgent字段中是不是有某些标识性子串就可以。比如,IE11以下的的版本可以以compatible和MSIE作为标识。IE11可以根据Trident和rv:11.0作为标识。
具体判断如下:
function isIE() {
let { userAgent } = window.navigator;
const ie_other = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1;
const ie_11 = userAgent.indexOf('trident') > -1 && userAgent.indexOf('rv:11.0') > -1;
if(ie_other || ie_11) {
return true;
}
return false;
}
获取IE浏览器版本,可根据MSIE后的数字获取:
function version_IE() {
let { userAgent } = window.navigator;
const ie_other = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1;
const ie_11 = userAgent.indexOf('trident') > -1 && userAgent.indexOf('rv:11.0') > -1;
if(ie_other){
return String(String(userAgent.match(/MSIE \d+.\d+/))).match(/\d+.\d+/);
} else if (ie_11) {
return 11.0;
}
return null;
}