在JavaScript中检测IE版本(在v9之前)

如果他们正在使用v9之前的Internet Explorer版本,我想将我们的网站用户跳转到错误页面。 只是不值得花时间和金钱来支持IE pre-v9 。 所有其他非IE浏览器的用户都很好,不应该被反弹。 这是build议的代码:

 if(navigator.appName.indexOf("Internet Explorer")!=-1){ //yeah, he's using IE var badBrowser=( navigator.appVersion.indexOf("MSIE 9")==-1 && //v9 is ok navigator.appVersion.indexOf("MSIE 1")==-1 //v10, 11, 12, etc. is fine too ); if(badBrowser){ // navigate to error page } } 

这个代码会诀窍吗?

为了避免一些可能会以我的方式发表的意见:

  1. 是的,我知道用户可以伪造他们的useragentstring。 我不关心。
  2. 是的,我知道编程专业人员更喜欢嗅探function支持而不是浏览器types,但是我不觉得这种方法在这种情况下是合理的。 我已经知道,所有(相关的)非IE浏览器都支持我需要的function,所有pre-v9 IE浏览器都不支持。 检查整个网站的function将是一个浪费。
  3. 是的,我知道有人试图访问使用IE v1 (或> = 20)的网站不会得到“badBrowser”设置为true,警告页面将不会正确显示。 这是我们愿意承担的风险。
  4. 是的,我知道微软有“有条件的评论”,可以用于精确的浏览器版本检测。 IE不再支持IE 10以上的条件注释,使得这种方法绝对无用。

任何其他明显的问题要注意?

这是我喜欢的方式。 它给予最大的控制。 (注意:条件语句只在IE5-9中支持)

首先正确设置你的ie类

 <!DOCTYPE html> <!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html> <!--<![endif]--> <head> 

然后,您可以使用CSS来创build样式exception,或者,如果您需要,可以添加一些简单的JavaScript:

 (function ($) { "use strict"; // Detecting IE var oldIE; if ($('html').is('.lt-ie7, .lt-ie8, .lt-ie9')) { oldIE = true; } if (oldIE) { // Here's your JS for IE.. } else { // ..And here's the full-fat code for everyone else } }(jQuery)); 

感谢Paul Irish 。

返回IE版本或者不IE返回false

 function isIE () { var myNav = navigator.userAgent.toLowerCase(); return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false; } 

例:

 if (isIE () == 8) { // IE8 code } else { // Other versions IE or not IE } 

要么

 if (isIE () && isIE () < 9) { // is IE version less than 9 } else { // is IE 9 and later or not IE } 

要么

 if (isIE()) { // is IE } else { // Other browser } 

如果没有人添加了addEventLister方法,并且您使用的是正确的浏览器模式,那么您可以检查IE 8或更less

 if (window.attachEvent && !window.addEventListener) { // "bad" IE } 

传统的Internet Explorer和attachEvent(MDN)

使用条件注释。 您试图检测IE <9的用户,条件注释将在这些浏览器中工作; 在其他浏览器(IE> = 10和非IE)中,注释将被视为正常的HTML注释,这就是它们的内容。

HTML示例:

 <!--[if lt IE 9]> WE DON'T LIKE YOUR BROWSER <![endif]--> 

如果你需要的话,你也可以纯粹用脚本来做到这一点:

 var div = document.createElement("div"); div.innerHTML = "<!--[if lt IE 9]><i></i><![endif]-->"; var isIeLessThan9 = (div.getElementsByTagName("i").length == 1); if (isIeLessThan9) { alert("WE DON'T LIKE YOUR BROWSER"); } 

轻松检测MSIE(v6 – v7 – v8 – v9 – v10 – v11):

 if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { // MSIE } 

为了可靠地过滤IE8和更老版本,可以使用检查全局对象 :

 if (document.all && !document.addEventListener) { alert('IE8 or lower'); } 

这是AngularJS 检查 IE的方式

 /** * documentMode is an IE-only property * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx */ var msie = document.documentMode; if (msie < 9) { // code for IE < 9 } 

此函数将返回IE主版本号作为整数,如果浏览器不是Internet Explorer,则返回undefined 。 这与所有的用户代理解决scheme一样,对于用户代理欺骗(自从版本8以来一直是IE的官方特征)是不可感知的。

 function getIEVersion() { var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:)(\d+)/); return match ? parseInt(match[1]) : undefined; } 

使用条件注释在JS中检测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; }()); 

这对我有用。 我用它作为redirect到一个页面,解释了为什么我们不喜欢<IE9,并提供了我们喜欢的浏览器的链接。

 <!--[if lt IE 9]> <meta http-equiv="refresh" content="0;URL=http://google.com"> <![endif]--> 

使用function检测(IE7 +,IE7之前的浏览器检测为7)检测IE版本:

 var ie = (function (){ if (window.ActiveXObject === undefined) return null; if (!document.querySelector) return 7; if (!document.addEventListener) return 8; if (!window.atob) return 9; if (!document.__proto__) return 10; return 11; })(); 

编辑:我已经创build了一个凉亭/ npm回购为您的方便: ie版本

你的代码可以做检查,但正如你所想,如果有人试图访问您的网页使用IE V1或> V19不会得到错误,所以可能会更安全地使用正则expression式检查如下面的代码:

 var userAgent = navigator.userAgent.toLowerCase(); // Test if the browser is IE and check the version number is lower than 9 if (/msie/.test(userAgent) && parseFloat((userAgent.match(/.*(?:rv|ie)[\/: ](.+?)([ \);]|$)/) || [])[1]) < 9) { // Navigate to error page } 

在Microsoft参考页上注明的版本10中不再支持条件注释。

 var ieDetector = function() { var browser = { // browser object verIE: null, docModeIE: null, verIEtrue: null, verIE_ua: null }, tmp; tmp = document.documentMode; try { document.documentMode = ""; } catch (e) {}; browser.isIE = typeof document.documentMode == "number" || eval("/*@cc_on!@*/!1"); try { document.documentMode = tmp; } catch (e) {}; // We only let IE run this code. if (browser.isIE) { browser.verIE_ua = (/^(?:.*?[^a-zA-Z])??(?:MSIE|rv\s*\:)\s*(\d+\.?\d*)/i).test(navigator.userAgent || "") ? parseFloat(RegExp.$1, 10) : null; var e, verTrueFloat, x, obj = document.createElement("div"), CLASSID = [ "{45EA75A0-A269-11D1-B5BF-0000F8051515}", // Internet Explorer Help "{3AF36230-A269-11D1-B5BF-0000F8051515}", // Offline Browsing Pack "{89820200-ECBD-11CF-8B85-00AA005B4383}" ]; try { obj.style.behavior = "url(#default#clientcaps)" } catch (e) {}; for (x = 0; x < CLASSID.length; x++) { try { browser.verIEtrue = obj.getComponentVersion(CLASSID[x], "componentid").replace(/,/g, "."); } catch (e) {}; if (browser.verIEtrue) break; }; verTrueFloat = parseFloat(browser.verIEtrue || "0", 10); browser.docModeIE = document.documentMode || ((/back/i).test(document.compatMode || "") ? 5 : verTrueFloat) || browser.verIE_ua; browser.verIE = verTrueFloat || browser.docModeIE; }; return { isIE: browser.isIE, Version: browser.verIE }; }(); document.write('isIE: ' + ieDetector.isIE + "<br />"); document.write('IE Version Number: ' + ieDetector.Version); 

对于10和11:

您可以使用js并在html中添加一个类来维护条件注释的标准:

  var ua = navigator.userAgent, doc = document.documentElement; if ((ua.match(/MSIE 10.0/i))) { doc.className = doc.className + " ie10"; } else if((ua.match(/rv:11.0/i))){ doc.className = doc.className + " ie11"; } 

或者使用像bowser一样的lib:

https://github.com/ded/bowser

或用于function检测的modernizr:

http://modernizr.com/

要检测Internet Explorer 10 | 11,可以在body标签后立即使用这个小脚本:

在我的情况下,我使用jQuery库加载头。

 <!DOCTYPE HTML> <html> <head> <script src="jquery-1.11.0.min.js"></script> </head> <body> <script>if (navigator.appVersion.indexOf('Trident/') != -1) $("body").addClass("ie10");</script> </body> </html> 

这已经被解决了,但这只是你需要的。

 !!navigator.userAgent.match(/msie\s[5-8]/i) 
 var Browser = new function () { var self = this; var nav = navigator.userAgent.toLowerCase(); if (nav.indexOf('msie') != -1) { self.ie = { version: toFloat(nav.split('msie')[1]) }; }; }; if(Browser.ie && Browser.ie.version > 9) { // do something } 

根据微软的说法,下面是最好的解决scheme,它也很简单:

 function getInternetExplorerVersion() // Returns the version of Internet Explorer or a -1 // (indicating the use of another browser). { var rv = -1; // Return value assumes failure. if (navigator.appName == 'Microsoft Internet Explorer') { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat( RegExp.$1 ); } return rv; } function checkVersion() { var msg = "You're not using Internet Explorer."; var ver = getInternetExplorerVersion(); if ( ver > -1 ) { if ( ver >= 8.0 ) msg = "You're using a recent copy of Internet Explorer." else msg = "You should upgrade your copy of Internet Explorer."; } alert( msg ); } 

我会build议不要重写这个代码的无数次。 我build议你使用Conditionizr库( http://conditionizr.com/ ),它能够testing特定的IE版本以及其他浏览器,操作系统,甚至是否存在Retina显示器。

只包含您需要的特定testing的代码,而且您还可以获得经过多次迭代(并且易于升级而不会破坏您的代码)的testing库的好处。

它还与Modernizr很好地相互配合,可以处理所有这些情况下,您最好testing一个特定的function,而不是一个特定的浏览器。

我喜欢这样做:

 <script> function isIE () { var myNav = navigator.userAgent.toLowerCase(); return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false; } var ua = window.navigator.userAgent; //Internet Explorer | if | 9-11 if (isIE () == 9) { alert("Shut down this junk! | IE 9"); } else if (isIE () == 10){ alert("Shut down this junk! | IE 10"); } else if (ua.indexOf("Trident/7.0") > 0) { alert("Shut down this junk! | IE 11"); }else{ alert("Thank god it's not IE!"); } </script> 

这种检测IE的方法结合了优点,避免了使用条件注释和Owen使用用户代理的答案的弱点。

  • jKey的方法工作到版本9并且在IE 8和9中不受用户代理欺骗的影响。
  • 欧文的方法可能会在IE 5&6(报告7)上失败,容易受到UA欺骗,但是它可以检测到大于等于10的IE版本(现在还包括12,这就是Owen的回答)。

     // ---------------------------------------------------------- // A short snippet for detecting versions of IE // ---------------------------------------------------------- // If you're not in IE (or IE version is less than 5) then: // ie === undefined // Thus, to detect IE: // if (ie) {} // And to detect the version: // ie === 6 // IE6 // ie > 7 // IE8, IE9 ... // ---------------------------------------------------------- var ie = (function(){ var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0] ); if (v <= 4) { // Check for IE>9 using user agent var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:|Edge\/)(\d+)/); v = match ? parseInt(match[1]) : undefined; } return v; }()); 

这可以用来为包含IE版本的文档设置有用的类:

  if (ie) { document.documentElement.className += ' ie' + ie; if (ie < 9) document.documentElement.className += ' ieLT9'; } 

请注意,如果IE处于兼容模式,它将检测正在使用的兼容模式。 另外请注意,IE版本主要用于旧版本(<10); 更高的版本更符合标准,可能更好地使用诸如modernizr.js之类的东西来检查特征。

我为此做了一个方便的下划线混合。

 _.isIE(); // Any version of IE? _.isIE(9); // IE 9? _.isIE([7,8,9]); // IE 7, 8 or 9? 
 _.mixin({ isIE: function(mixed) { if (_.isUndefined(mixed)) { mixed = [7, 8, 9, 10, 11]; } else if (_.isNumber(mixed)) { mixed = [mixed]; } for (var j = 0; j < mixed.length; j++) { var re; switch (mixed[j]) { case 11: re = /Trident.*rv\:11\./g; break; case 10: re = /MSIE\s10\./g; break; case 9: re = /MSIE\s9\./g; break; case 8: re = /MSIE\s8\./g; break; case 7: re = /MSIE\s7\./g; break; } if (!!window.navigator.userAgent.match(re)) { return true; } } return false; } }); console.log(_.isIE()); console.log(_.isIE([7, 8, 9])); console.log(_.isIE(11)); 
 <script src="ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 

我发现检查IE版本的最全面的JS脚本是http://www.pinlady.net/PluginDetect/IE/ 。 整个图书馆在http://www.pinlady.net/PluginDetect/Browsers/

使用IE10,不再支持条件语句。

用IE11,用户代理不再包含MSIE。 此外,使用用户代理是不可靠的,因为可以修改。

使用PluginDetect JS脚本,您可以检测IE并通过使用针对特定IE版本的非常具体和精心devise的代码来检测确切的版本。 当你关心你正在使用什么版本的浏览器时,这是非常有用的。

我意识到我在这里的晚会有点晚,但是我一直在检查一个简单的一行方式,以提供关于浏览器是否是IE浏览器的反馈,以及它是从哪个版本开始的。 我没有编码版本11,所以也许需要一些修改。

然而,这是代码,它作为一个对象具有一个属性和一个方法,并依赖于对象检测,而不是抓取导航器对象(这是大量的缺陷,因为它可以被欺骗)。

 var isIE = { browser:/*@cc_on!@*/false, detectedVersion: function () { return (typeof window.atob !== "undefined") ? 10 : (typeof document.addEventListener !== "undefined") ? 9 : (typeof document.querySelector !== "undefined") ? 8 : (typeof window.XMLHttpRequest !== "undefined") ? 7 : (typeof document.compatMode !== "undefined") ? 6 : 5; } }; 

用法isIE.browser是一个返回布尔值的属性,依赖于有条件的注释方法isIE.detectedVersion() ,它返回一个介于5和10之间的数字。我假设任何低于6的值,领土,你会比一个class轮更高的东西,任何高于10的东西,你是在更新的领土。 我已经读了一些关于IE11不支持条件注释,但我还没有完全调查,也许是为了以后的日子。

无论如何,它是一个单行的,它将涵盖IE浏览器和版本检测的基础知识。 这并不完美,但它很小,很容易修改。

仅供参考,如果有人对如何真正实现这一点有任何疑问,那么以下条件应该有所帮助。

 var isIE = { browser:/*@cc_on!@*/false, detectedVersion: function () { return (typeof window.atob !== "undefined") ? 10 : (typeof document.addEventListener !== "undefined") ? 9 : (typeof document.querySelector !== "undefined") ? 8 : (typeof window.XMLHttpRequest !== "undefined") ? 7 : (typeof document.compatMode !== "undefined") ? 6 : 5; } }; /* testing IE */ if (isIE.browser) { alert("This is an IE browser, with a detected version of : " + isIE.detectedVersion()); } 

检测IE及其版本并不容易,只需要一点本地/香草的Javascript:

 var uA = navigator.userAgent; var browser = null; var ieVersion = null; if (uA.indexOf('MSIE 6') >= 0) { browser = 'IE'; ieVersion = 6; } if (uA.indexOf('MSIE 7') >= 0) { browser = 'IE'; ieVersion = 7; } if (document.documentMode) { // as of IE8 browser = 'IE'; ieVersion = document.documentMode; } 

这是一个使用它的方法:

 if (browser == 'IE' && ieVersion <= 9) document.documentElement.className += ' ie9-'; 

适用于所有IE版本,包括较低版本的Compatability View / Mode, documentMode是IE专有的。

如果你需要浏览IE浏览器版本,那么你可以按照下面的代码。 此代码适用于从IE6到IE11的版本

 <!DOCTYPE html> <html> <body> <p>Click on Try button to check IE Browser version.</p> <button onclick="getInternetExplorerVersion()">Try it</button> <p id="demo"></p> <script> function getInternetExplorerVersion() { var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); var rv = -1; if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number { if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) { //For IE 11 > if (navigator.appName == 'Netscape') { var ua = navigator.userAgent; var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) { rv = parseFloat(RegExp.$1); alert(rv); } } else { alert('otherbrowser'); } } else { //For < IE11 alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)))); } return false; }} </script> </body> </html> 

窗口运行IE10将自动更新到IE11 +,并将标准化为W3C

现在,我们不需要支持IE8-

  <!DOCTYPE html> <!--[if lt IE 9]><html class="ie ie8"><![endif]--> <!--[if IE 9]><html class="ie ie9"><![endif]--> <!--[if (gt IE 9)|!(IE)]><!--><html><!--<![endif]--> <head> ... <!--[if lt IE 8]><meta http-equiv="Refresh" content="0;url=/error-browser.html"><![endif]-- ... </head> 
 var isIE9OrBelow = function() { return /MSIE\s/.test(navigator.userAgent) && parseFloat(navigator.appVersion.split("MSIE")[1]) < 10; } 
 if (!document.addEventListener) { // ie8 } else if (!window.btoa) { // ie9 } // others 
 // Detect ie <= 10 var ie = /MSIE ([0-9]+)/g.exec(window.navigator.userAgent)[1] || undefined; console.log(ie); // Return version ie or undefined if not ie or ie > 10