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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10964966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:48:22  来源:igfitidea点击:

Detect IE version (prior to v9) in JavaScript

javascriptinternet-exploreruser-agentbrowser-detection

提问by Chad Decker

I want to bounce users of our web site to an error page if they're using a version of Internet Explorerprior to v9. It's just not worth our time and money to support IE pre-v9. Users of all other non-IE browsers are fine and shouldn't be bounced. Here's the proposed code:

如果我们网站的用户使用的是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
    }
}

Will this code do the trick?

这段代码能解决问题吗?

To head off a few comments that will probably be coming my way:

阻止一些可能会出现在我身上的评论:

  1. Yes, I know that users can forge their useragentstring. I'm not concerned.
  2. Yes, I know that programming pros prefer sniffing out feature-support instead of browser-type but I don't feel this approach makes sense in this case. I already know that all (relevant) non-IE browsers support the features that I need and that all pre-v9 IEbrowsers don't. Checking feature by feature throughout the site would be a waste.
  3. Yes, I know that someone trying to access the site using IE v1(or >= 20) wouldn't get 'badBrowser' set to true and the warning page wouldn't be displayed properly. That's a risk we're willing to take.
  4. Yes, I know that Microsoft has "conditional comments" that can be used for precise browser version detection. IE no longer supports conditional comments as of IE 10, rendering this approach absolutely useless.
  1. 是的,我知道用户可以伪造他们的useragent字符串。我不担心。
  2. 是的,我知道编程专业人士更喜欢嗅探功能支持而不是浏览器类型,但我认为这种方法在这种情况下没有意义。我已经知道所有(相关)非 IE 浏览器都支持我需要的功能,而所有pre-v9 IE浏览器都不支持。在整个站点中逐个检查功能将是一种浪费。
  3. 是的,我知道有人尝试使用IE v1(或 >= 20)访问站点不会将 'badBrowser' 设置为 true,并且警告页面将无法正确显示。这是我们愿意承担的风险。
  4. 是的,我知道微软有“条件注释”,可用于精确的浏览器版本检测。从 开始,IE 不再支持条件注释IE 10,因此这种方法完全无用。

Any other obvious issues to be aware of?

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

回答by Jezen Thomas

This is my preferred way of doing it. It gives maximum control. (Note: Conditional statements are only supported in IE5 - 9.)

这是我的首选方式。它提供了最大程度的控制。(注意:条件语句仅在 IE5-9 中受支持。)

First set up your ie classes correctly

首先正确设置您的 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>

Then you can just use CSS to make style exceptions, or, if you require, you can add some simple JavaScript:

然后你可以使用 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));

Thanks to Paul Irish.

感谢保罗爱尔兰

回答by weroro

Return IE version or if not IE return false

返回 IE 版本,否则 IE 返回 false

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

Example:

例子:

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

or

或者

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

or

或者

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

回答by Andreas

If nobody else has added an addEventLister-method and you're using the correct browser mode then you could check for IE 8 or less with

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

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

Legacy Internet Explorer and attachEvent (MDN)

旧版 Internet Explorer 和 attachEvent (MDN)

回答by Tim Down

Use conditional comments. You're trying to detect users of IE < 9 and conditional comments will work in those browsers; in other browsers (IE >= 10 and non-IE), the comments will be treated as normal HTML comments, which is what they are.

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

Example HTML:

示例 HTML:

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

You can also do this purely with script, if you need:

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

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");
}

回答by EpokK

To detect MSIE (v6 - v7 - v8 - v9 - v10 - v11) easily :

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

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

回答by iurii

Here is the way AngularJS checksfor IE

这是 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
}

回答by Beaudinn Greve

To reliably filter IE8 and older, checking global objectscan be used:

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

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

回答by Gabriel Llamas

Detecting IE version using feature detection (IE6+, browsers prior to IE6 are detected as 6, returns null for non-IE browsers):

使用特征检测检测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;
})();

Edit: I've created a bower/npm repo for your convenience: ie-version

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

Update:

更新:

a more compact version can be written in one line as:

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

return window.ActiveXObject === undefined ? null : !window.XMLHttpRequest ? 6 : !document.querySelector ? 7 : !document.addEventListener ? 8 : !window.atob ? 9 : !document.__proto__ ? 10 : 11;

回答by Owen

This function will return the IE major version number as an integer, or undefinedif the browser isn't Internet Explorer. This, like all user agent solutions, is suceptible to user agent spoofing (which has been an official feature of IE since version 8).

undefined如果浏览器不是 Internet Explorer ,此函数将以整数形式返回 IE 主版本号。这与所有用户代理解决方案一样,容易受到用户代理欺骗(自版本 8 以来一直是 IE 的官方功能)。

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

回答by jKey

Detect IE in JS using conditional comments

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

}());