主要判斷世界五大主流瀏覽器內核,其中IE瀏覽器可以精確到版本號(IE5-IE11,同時考慮了兼容模式),同時支持判斷國內大部分套殼瀏覽器
function browerType() {
var ua = navigator.userAgent.toLocaleLowerCase();
// 判斷是否爲IE(第一個是正常的IE,第二個是Edge,第三個是IE11)
var isIE = (ua.indexOf("compatible") > -1 && ua.indexOf("msie") > -1) || (ua.indexOf("edge") > -1) || (ua.indexOf(
'trident') > -1 && ua.indexOf("rv:11.0") > -1);
// 判斷是否爲IE5678,!+[1,] 在IE5678返回true,在IE9、IE10、IE11返回false
var isLteIE8 = isIE && !+[1, ];
// 用於防止因通過IE8+的文檔兼容性模式設置文檔模式,導致版本判斷失效
var dm = document.documentMode,
isIE5,
isIE6,
isIE7,
isIE8,
isIE9,
isIE10,
isIE11;
if (dm) {
isIE5 = dm === 5;
isIE6 = dm === 6;
isIE7 = dm === 7;
isIE8 = dm === 8;
isIE9 = dm === 9;
isIE10 = dm === 10;
isIE11 = dm === 11;
} else {
// 判斷是否爲IE5,IE5的文本模式爲怪異模式(quirks),真實的IE5.5瀏覽器中沒有document.compatMode屬性
isIE5 = (isLteIE8 && (!document.compatMode || document.compatMode === 'BackCompat'));
// 判斷是否爲IE6,IE7開始有XMLHttpRequest對象
isIE6 = isLteIE8 && !isIE5 && !XMLHttpRequest;
// 判斷是否爲IE7,IE8開始有document.documentMode屬性
isIE7 = isLteIE8 && !isIE6 && !document.documentMode;
// 判斷是否IE8
isIE8 = isLteIE8 && document.documentMode;
// 判斷IE9,IE9嚴格模式中函數內部this不爲undefined
isIE9 = !isLteIE8 && (function () {
"use strict";
return !!this;
}());
// 判斷IE10,IE10開始支持嚴格模式,嚴格模式中函數內部this爲undefined
isIE10 = isIE && !!document.attachEvent && (function () {
"use strict";
return !this;
}());
// 判斷IE11,IE11開始移除了attachEvent屬性
isIE11 = isIE && !document.attachEvent;
};
// 因爲字符串存在覆蓋重複原因,判斷順序不可隨意修改
isIE5 ? document.write('IE5') :
isIE6 ? document.write('IE6') :
isIE7 ? document.write('IE7') :
isIE8 ? document.write('IE8') :
isIE9 ? document.write('IE9') :
isIE10 ? document.write('IE10') :
(ua.indexOf('green') > -1) ? document.write('綠色瀏覽器') :
isIE11 ? document.write('IE11') :
(ua.indexOf('qq') > -1) ? document.write('QQ瀏覽器') :
(ua.indexOf('bidu') > -1) ? document.write('百度瀏覽器') :
(ua.indexOf('lb') > -1) ? document.write('獵豹瀏覽器') :
(ua.indexOf('world') > -1) ? document.write('世界之窗瀏覽器') :
(ua.indexOf('2345') > -1) ? document.write('2345瀏覽器') :
(ua.indexOf('maxthon') > -1) ? document.write('傲遊瀏覽器') :
(ua.indexOf('tao') > -1) ? document.write('淘寶瀏覽器') :
(ua.indexOf('ubrowser') > -1) ? document.write('UC瀏覽器') :
(ua.indexOf('coolnovo') > -1) ? document.write('楓葉瀏覽器') :
(ua.indexOf('opr') > -1) ? document.write('opera瀏覽器') :
(ua.indexOf('se') > -1) ? document.write('搜狗瀏覽器') :
(ua.indexOf('firefox') > -1) ? document.write('firefox瀏覽器') :
(ua.indexOf('safari') > -1 && ua.indexOf("version") > -1) ? document.write('safari瀏覽器') :
(window.navigator.mimeTypes[40] || !window.navigator.mimeTypes.length) ? document.write('360瀏覽器') :
(ua.indexOf("chrome") > -1 && window.chrome) ? document.write('chrome瀏覽器') : document.write('其他');
}
browerType();