IE浏览器检测的方法
检测浏览器版本是很多前端工作者在写跨浏览器的js程序时一项非常重要的工作,我们经常要为不同的浏览器写不同的分支代码。如今检测浏览器方式也是五花八门,这里我们就把这些浏览器检测方式都记录下载。本文最后还记录了一组代码,运用IE浏览器的条件编译来检测IE浏览器的各版本。
传统一般都是采用user-agent的检测方式,它检测目标浏览器的确切型号,包括浏览器的名称和版本。其实就是一个字符串,用navigator.userAgen或navigator.appName获取。如下:
function isIE(){ return navigator.appName.indexOf("Microsoft Internet Explorer")!=-1 && document.all; } function isIE6() { return navigator.userAgent.split(";")[1].toLowerCase().indexOf("msie 6.0")=="-1"?false:true; } function isIE7(){ return navigator.userAgent.split(";")[1].toLowerCase().indexOf("msie 7.0")=="-1"?false:true; } function isIE8(){ return navigator.userAgent.split(";")[1].toLowerCase().indexOf("msie 8.0")=="-1"?false:true; } function isNN(){ return navigator.userAgent.indexOf("Netscape")!=-1; } function isOpera(){ return navigator.appName.indexOf("Opera")!=-1; } function isFF(){ return navigator.userAgent.indexOf("Firefox")!=-1; } function isChrome(){ return navigator.userAgent.indexOf("Chrome") > -1; }
目前比较流行的检测方式则是通过“对象/特征”来判断浏览器能力的方式。下面的addEvent代码就是使用了该方式。.addEventListener是w3c dom标准方式,而IE使用自己特有attachEvent。
//添加事件工具函数 function addEvent(el,type,handle){ if(el.addEventListener){//for standard browses el.addEventListener(type,handle,false); }else if(el.attachEvent){//for IE el.attachEvent("on"+event,handle); }else{//other el["on"+type]=handle; } }
在举几个列子:
1、talbe.cells只有IE/Opera支持。
2、innerText/insertAdjacentHTML除Firefox外,IE6/7/8/Safari/Chrome/Opera都支持。
3、window.external.AddFavorite用来在IE下添加到收藏夹。
4、window.sidebar.addPanel用来在Firefox下添加到收藏夹。
还有一种有趣的检测方式,暂且称为“浏览器缺陷或bug”方式,即某些表现不是浏览器厂商刻意实现的。如下:
var isIE = !+"v1"; var isIE = !-[1,]; var isIE = "v"=="v"; isSafari=/a/.__proto__=='//'; isOpera=!!window.opera;
isIE = "v" == "v" 方式IE9已经修复该bug,不能用此方式判断IE浏览器了(2010-6-29用IE9平台预览第三版测试的)
最经典的莫过于 !-[1,] 的判断方式,仅仅用了6 bytes判定IE浏览器,创世界最短纪录,这组代码利用了数组[1,]的length。
IE浏览器检测代码:
// ---------------------------------------------------------- // A short snippet for detecting versions of IE in JavaScript // without resorting to user-agent sniffing // ---------------------------------------------------------- // If you're not in IE (or IE version is less than 5) then: // ie === undefined // If you're in IE (>=5) then you can determine which version: // ie === 7; // IE7 // Thus, to detect IE: // if (ie) {} // And to detect the version: // ie === 6 // IE6 // ie > 7 // IE8, IE9 ... // ie < 9 // Anything less than IE9 // ---------------------------------------------------------- //UPDATE: Now using Live NodeList idea from @jdalton var ie = (function() { var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0] ); return v > 4 ? v : undef; })();
这个代码的意图就是.通过while循环.将条件编译写入到div即页面中,然后直接取注释下的这个元素,直到取不到就退出循环。这样就获得了IE的最终版本,如果不是IE那么就是undefined。

我觉得user-agent检测的觉得IE浏览器版本不太准确,还会经常出错。而且浏览器还可以伪造user-agent信息欺骗。