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

Cha*_*ker 246 javascript internet-explorer user-agent browser-detection

如果他们使用的是Internet Explorerv9之前的版本,我想将我们网站的用户反弹到错误页面.我们的时间和金钱都不值得支持IE pre-v9.所有其他非IE浏览器的用户都很好,不应该被退回.这是建议的代码:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

这个代码会起作用吗?

关闭一些可能会出现的评论:

  1. 是的,我知道用户可以伪造他们的useragent字符串.我并不担心.
  2. 是的,我知道编程专家更喜欢嗅出功能支持而不是浏览器类型,但我觉得这种方法在这种情况下没有意义.我已经知道所有(相关的)非IE浏览器都支持我需要的功能,并且所有pre-v9 IE浏览器都不支持.在整个站点中按功能检查功能将是一种浪费.
  3. 是的,我知道有人试图使用IE v1(或> = 20)访问该网站不会将'badBrowser'设置为true,并且警告页面将无法正确显示.这是我们愿意承担的风险.
  4. 是的,我知道微软有"条件评论",可以用于精确的浏览器版本检测.IE不再支持条件注释IE 10,使得这种方法绝对无用.

还有其他明显的问题需要注意吗?

Jez*_*mas 354

这是我的首选方式.它提供了最大的控制.(注意:条件语句仅在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>
Run Code Online (Sandbox Code Playgroud)

然后你可以使用CSS来制作样式异常,或者,如果需要,你可以添加一些简单的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));
Run Code Online (Sandbox Code Playgroud)

感谢Paul Irish.

  • 鉴于OP要求一个纯粹的JavaScript解决方案,我相信下面的@Tim Down的答案更好,因为它不涉及更改现有的HTML,而且它不使用jQuery:http://stackoverflow.com/a /十三万四千一百二十零分之一千○九十六万五千二百○三 (21认同)

小智 161

返回IE版本或如果不是IE返回false

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

例:

if (isIE () == 8) {
 // IE8 code
} else {
 // Other versions IE or not IE
}
Run Code Online (Sandbox Code Playgroud)

要么

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

要么

if (isIE()) {
 // is IE
} else {
 // Other browser
}
Run Code Online (Sandbox Code Playgroud)

  • 不适用于IE11.从IE 11开始,他们将UA字符串更改为"mozilla/5.0(windows nt 6.3; wow64; trident/7.0; .net4.0e; .net4.0c; media center pc 6.0; .net clr 3.5.30729 ;. net clr 2.0.50727; .net clr 3.0.30729; rv:11.0)like gecko"` (36认同)
  • 请注意,在FF中,"false <9"为"true".所以,条件应该是`if(isIE()&& isIE()<9){` (22认同)
  • 批准的答案是如何检测HTML中的IE版本.这回答了原始问题. (4认同)
  • @DeadlyChambers或许它是在IE7标准模式下运行的?http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx (3认同)
  • @PrasadGayan - Microsoft Edge不是Internet Explorer.因此,返回false似乎是正确的事情. (2认同)

And*_*eas 120

如果没有其他人添加了addEventLister-method并且您使用的是正确的浏览器模式,那么您可以检查IE 8或更低版本

if (window.attachEvent && !window.addEventListener) {
    // "bad" IE
}
Run Code Online (Sandbox Code Playgroud)

旧版Internet Explorer和attachEvent(MDN)

  • 这似乎是在JavaScript中完全检测IE <= 8的最有效方法 - 对于像我这样寻找方法的人来说非常棒. (7认同)
  • 虽然这是一种"易于使用"的解决方案,但它存在一些风险.您公司中的任何人(不知道您的解决方案)都可以实现"addEventListener"或"attachEvent"来处理IE 8中缺少它.然后,您的代码将停止工作. (7认同)

Tim*_*own 114

使用条件评论.您正在尝试检测IE <9的用户,并且条件注释将在这些浏览器中起作用; 在其他浏览器(IE> = 10和非IE)中,注释将被视为普通的HTML注释,这就是它们的含义.

示例HTML:

<!--[if lt IE 9]>
WE DON'T LIKE YOUR BROWSER
<![endif]-->
Run Code Online (Sandbox Code Playgroud)

如果需要,您也可以使用脚本完成此操作:

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");
}
Run Code Online (Sandbox Code Playgroud)

  • @Tim Down的JavaScript版本的答案对我很有帮助.我用BrowserStack用Windows 7和IE 8,9,10和11测试它; 带有Safari 5.1,Firefox 28.0,Chrome 33.0和Opera 20.0的Mac OS X Snow Leopard; iPhone 5 Mobile Safari; 和Android三星Galaxy Tab 2 10.1 4.0.正如预期的那样,只有IE8报告它是IeLessThan9.太好了! (5认同)

Epo*_*okK 58

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

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

  • 最后一个答案没有讲述使用特征检测并实际回答问题. (11认同)
  • 我编辑我的答案以支持IE10和IE11. (2认同)

iur*_*rii 30

这是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
}
Run Code Online (Sandbox Code Playgroud)


Bea*_*eve 27

要可靠地过滤IE8及更早版本,可以使用检查全局对象:

if (document.all && !document.addEventListener) {
    alert('IE8 or lower');
}
Run Code Online (Sandbox Code Playgroud)

  • document.all - IE 11不支持 - https://msdn.microsoft.com/en-us/library/ie/ms537434%28v=vs.85%29.aspx (2认同)
  • @RajaKhoury-如果尝试测试IE &lt;9则很好-if条件将为false。 (2认同)

Gab*_*mas 17

使用特征检测检测IE版本(IE6 +,IE6之前的浏览器被检测为6,非IE浏览器返回null):

var ie = (function (){
    if (window.ActiveXObject === undefined) return null; //Not IE
    if (!window.XMLHttpRequest) return 6;
    if (!document.querySelector) return 7;
    if (!document.addEventListener) return 8;
    if (!window.atob) return 9;
    if (!document.__proto__) return 10;
    return 11;
})();
Run Code Online (Sandbox Code Playgroud)

编辑:为方便起见,我创建了一个bower/npm repo:ie-version

更新:

一个更紧凑的版本可以写成一行:

return window.ActiveXObject === undefined ? null : !window.XMLHttpRequest ? 6 : !document.querySelector ? 7 : !document.addEventListener ? 8 : !window.atob ? 9 : !document.__proto__ ? 10 : 11;
Run Code Online (Sandbox Code Playgroud)


Owe*_*wen 16

此函数将IE主要版本号作为整数返回,或者undefined如果浏览器不是Internet Explorer.与所有用户代理解决方案一样,它易受用户代理欺骗的影响(自版本8以来一直是IE的官方功能).

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


小智 15

使用条件注释检测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;

}());
Run Code Online (Sandbox Code Playgroud)


小智 12

这适合我.我将它用作重定向页面,解释了为什么我们不喜欢<IE9并提供我们喜欢的浏览器的链接.

<!--[if lt IE 9]>
<meta http-equiv="refresh" content="0;URL=http://google.com">
<![endif]-->
Run Code Online (Sandbox Code Playgroud)


Fon*_*hau 10

您的代码可以进行检查,但是如您所想,如果有人尝试使用IE v1或> v19访问您的页面将不会收到错误,那么可以更安全地使用Regex表达式进行检查,如下面的代码所示:

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
}
Run Code Online (Sandbox Code Playgroud)

  • @Jezen有时UA嗅探是要走的路:https://github.com/Modernizr/Modernizr/issues/538 (3认同)

小智 8

Microsoft参考页面上提到的IE 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);
Run Code Online (Sandbox Code Playgroud)

然后使用:

if((ieDetector.isIE) && (ieDetector.Version <= 9))
{

}
Run Code Online (Sandbox Code Playgroud)


Lik*_*iko 5

对于ie 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";
  }
Run Code Online (Sandbox Code Playgroud)

或者像bowser一样使用lib:

https://github.com/ded/bowser

或用于特征检测的现代化:

http://modernizr.com/

  • 我尝试了一些脚本和解决方案,但没有任何效果.然后我在项目中加入了bowser,它刚刚起作用.因此建议使用bowser. (2认同)