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

Detect IE version (prior to v9) in JavaScript

本文关键字:v9 之前 版本 IE JavaScript 检测      更新时间:2023-09-26

我想将我们网站的用户退回到错误页面,如果他们使用的是v9之前的版本Internet Explorer。只是不值得我们花时间和金钱来支持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
    }
}

这段代码能解决问题吗?

为了阻止一些可能会遇到的评论:

  1. 是的,我知道用户可以伪造他们的useragent字符串。我不担心。
  2. 是的,我知道编程专家更喜欢嗅探功能支持而不是浏览器类型,但我认为这种方法在这种情况下没有意义。我已经知道所有(相关的)非IE浏览器都支持我需要的功能,而所有pre-v9 IE浏览器都不支持。在整个站点中逐个检查功能将是一种浪费。
  3. 是的,我知道尝试使用 IE v1(或>= 20)访问该网站的人不会将"badBrowser"设置为 true,并且警告页面将无法正确显示。这是我们愿意承担的风险。
  4. 是的,我知道Microsoft有"条件注释",可用于精确的浏览器版本检测。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 来制作样式异常,或者,如果需要,你可以添加一些简单的 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));

感谢保罗·爱尔兰。

返回

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
}

使用条件注释。您正在尝试检测 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");
}

如果没有其他人添加addEventLister方法并且您使用正确的浏览器模式,那么您可以使用

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

Legacy Internet Explorer and attachEvent (MDN)

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

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

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

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

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

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

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

更新:

更紧凑的版本可以在一行中编写为:

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

此函数将以整数形式返回 IE 主要版本号,如果浏览器不是 Internet Explorer,则返回undefined。与所有用户代理解决方案一样,这容易受到用户代理欺骗的影响(自版本 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;
}());

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

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

您的代码可以执行检查,但正如您所想的,如果有人尝试使用 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
}

从版本 10 开始,IE 不再支持条件注释,如Microsoft参考页上所述。

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

然后使用:

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

对于 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";
  }

或者使用像 bowser 这样的库:

https://github.com/ded/bowser

或用于功能检测的现代化:

http://modernizr.com/

这已经被回答到死了,但这就是你所需要的。

!!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
}

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

就我而言,我使用在head中加载的jQuery库。

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

根据Microsoft的说法,以下是最好的解决方案,它也非常简单:

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

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

在 IE10 中,不再支持条件语句。

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

使用 PluginDetect JS 脚本,您可以使用针对特定 IE 版本的非常具体且精心设计的代码来检测 IE 并检测确切的版本。当您确切关心正在使用的浏览器版本时,这非常有用。

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

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

它还与 Modernizr 很好地融合在一起,它可以处理所有那些您最好测试特定功能而不是特定浏览器的情况。

我喜欢这样:

<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的方法结合了jKey使用条件注释的答案和Owen使用用户代理的答案的优点并避免了缺点。

  • jKey的方法适用于版本9,并且不受IE 8和9中的用户代理欺骗的影响。
  • 欧文的方法可能在IE 5和6(报告7)上失败,并且容易受到UA欺骗,但它可以检测到IE版本>= 10(现在也包括12,它晚于欧文的答案)。

    // ----------------------------------------------------------
    // 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="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

或干脆

//   IE 10: ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'; 
//   IE 11: ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'; 
// Edge 12: ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0'; 
// Edge 13: ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586'; 
var isIE = navigator.userAgent.match(/MSIE|Trident|Edge/)
var IEVersion = ((navigator.userAgent.match(/(?:MSIE |Trident.*rv:|Edge'/)('d+('.'d+)?)/)) || []) [1]

我意识到我在这里参加聚会有点晚了,但我一直在检查一个简单的单行方法来提供有关浏览器是否是 IE 以及从 10 开始的版本是什么的反馈。我还没有为版本 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 的东西,你都处于严重的老派领域,你会比一个衬里更强大,任何高于 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 版本,包括较低兼容性视图/模式下的较高版本,并且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