【问题标题】:How to detect IE11?如何检测IE11?
【发布时间】:2013-07-28 06:19:37
【问题描述】:

当我想检测 IE 时,我使用以下代码:

function getInternetExplorerVersion()
{
  var rv = -1;
  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 )
  {
    msg = "You are using IE " + ver;
  }
  alert( msg );
}

但是 IE11 正在返回“您没有使用 Internet Explorer”。如何检测?

【问题讨论】:

  • 任何基于用户代理的东西都是有缺陷的。欺骗太容易了,现在,这可能不是问题,但在我看来,浏览器检测脚本应该有相当大的机会检测到伪装。我使用条件 cmets 的组合,尝试强制 document.documentMode,然后按照下面的 Paul Sweatte 查看 window.MSInputMethodContext。我会发布我的代码,但它正在鞭打一匹死马。
  • IE11 有用户代理:Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) 像 Gecko Os 类型:6.1 - win7, 6.3 - win81
  • 在这里查看我的答案stackoverflow.com/questions/21825157/…
  • 这是我找到的最佳解决方案:stackoverflow.com/a/20201867/2047385 if (Object.hasOwnProperty.call(window, "ActiveXObject") && !window.ActiveXObject) { // is IE11 }

标签: internet-explorer debugging internet-explorer-11 browser-detection forward-compatibility


【解决方案1】:

IE11 不再报告为MSIE,根据this list of changes,这是为了避免误检测。

如果你真的想知道它是 IE,你可以做的是在 navigator.appName 返回 Netscape 时检测用户代理中的 Trident/ 字符串,类似于(未经测试的);

function getInternetExplorerVersion()
{
  var rv = -1;
  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 );
  }
  else 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 );
  }
  return rv;
}

console.log('IE version:', getInternetExplorerVersion());

请注意,IE11 (afaik) 仍处于预览阶段,用户代理可能会在发布前更改。

【讨论】:

  • it's intentional to avoid mis-detection - 遗憾的是,现在 IE11 发布了,我们的代码在 IE11 中被破坏,而正确检测 IE 本来可以工作...
  • 如果版本不太重要,我将此解决方案转换为布尔值function isIE() { return ((navigator.appName == 'Microsoft Internet Explorer') || ((navigator.appName == 'Netscape') && (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null))); }
  • @lzkata - 根据html5 spec here,IE 实际上遵循标准。所以是的,这是故意的,但它符合新标准(弃用旧的 html api。)
  • “他们这样做是故意的。他们想像这样破坏浏览器检测脚本。”来自stackoverflow.com/a/18872067/1066234 ...实际上应该是:'他们想让十亿个网站像这样崩溃。'
  • 这对我有用:var isIE11 = !!navigator.userAgent.match(/Trident\/7\./);source
【解决方案2】:

使用!(window.ActiveXObject) && "ActiveXObject" in window 显式检测IE11。

要检测任何 IE(pre-Edge,“Trident”)版本,请改用 "ActiveXObject" in window

【讨论】:

  • 这篇微软文章建议这个解决方案可能不再有效msdn.microsoft.com/en-us/library/ie/dn423948(v=vs.85).aspx
  • 其实这篇文章描述了我的方法起作用的原因。尝试访问window.ActiveXObject,如文章中所述,现在在 IE11(以及非 Microsoft 浏览器)中返回 undefined。使用 javascript in 运算符的测试在所有 Microsoft 浏览器中返回 true,所以两者在 IE11 中严格来说是这种情况。如果 Microsoft 对 in 运算符的行为进行更改,是的,此方法将中断。
  • "ActiveXObject" in window 在 Edge 中返回 False。
  • @Neo Edge 不是 IE,OP 的问题是如何检测 IE11
  • @mastazi 是的,但在这个答案中,提到 ActiveXObject 可用于检测任何 IE 版本。虽然 Edge 是否应该被称为 IE 的一个版本是有争议的(微软肯定不想称它为一个),但对于许多开发人员来说,IE 已经成为任何默认微软浏览器的同义词。
【解决方案3】:

使用MSInputMethodContext 作为特征检测检查的一部分。例如:

//Appends true for IE11, false otherwise
window.location.hash = !!window.MSInputMethodContext && !!document.documentMode;

参考文献

【讨论】:

  • 这在我看来更加健壮。当然,任何基于用户代理的东西都是毫无用处的。
  • 这代替了 ActiveXObject。非常感谢
  • @tdakhla 已更新以过滤掉 IE Edge。
  • 对于任何这些似乎不起作用的答案,重要的是要检查仿真设置,我打算将此答案标记为不正确,但后来我检查了仿真并看到一些Intranet 兼容性设置覆盖了显示模式,一旦将其从方程式中取出,此解决方案对我来说效果很好。
  • 刚刚在非 IE、IE8、9、10、Edge 14、15 中确认 #false#true 仅在 IE11 中。未在激活文档模式的情况下进行测试。用 Browserstack 测试。
【解决方案4】:

我已经阅读了您的答案并进行了混合。它似乎适用于 Windows XP(IE7/IE8) 和 Windows 7 (IE9/IE10/IE11)。

function ie_ver(){  
    var iev=0;
    var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
    var trident = !!navigator.userAgent.match(/Trident\/7.0/);
    var rv=navigator.userAgent.indexOf("rv:11.0");

    if (ieold) iev=new Number(RegExp.$1);
    if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
    if (trident&&rv!=-1) iev=11;

    return iev;         
}

当然,如果我返回 0,则表示没有 IE。

【讨论】:

    【解决方案5】:

    从 User-Agent 获取 IE 版本

    var ie = 0;
    try { ie = navigator.userAgent.match( /(MSIE |Trident.*rv[ :])([0-9]+)/ )[ 2 ]; }
    catch(e){}
    

    它是如何工作的: 用户代理字符串for all IE versions 包含“MSIE space version”或“Trident ”部分其他文本 rv 空格或冒号 版本”。知道了这一点,我们从String.match() 正则表达式中获取版本号。 try-catch 块用于缩短代码,否则我们需要测试非 IE 浏览器的数组边界。

    注意:用户代理可能会被欺骗或省略,如果用户将浏览器设置为“兼容模式”,有时可能会无意中出现。虽然这在实践中似乎不是什么大问题。


    获取没有 User-Agent 的 IE 版本

    var d = document, w = window;
    var ie = ( !!w.MSInputMethodContext ? 11 : !d.all ? 99 : w.atob ? 10 : 
    d.addEventListener ? 9 : d.querySelector ? 8 : w.XMLHttpRequest ? 7 : 
    d.compatMode ? 6 : w.attachEvent ? 5 : 1 );
    

    工作原理:每个版本的 IE 都增加了对 additional features 的支持,而这在以前的版本中是没有的。所以我们可以以自上而下的方式测试特征。为简洁起见,此处使用ternary 序列,尽管if-thenswitch 语句也可以工作。变量ie 设置为整数 5-11,或 1 表示较旧,或 99 表示较新/非 IE。如果您只想准确测试 IE 1-11,可以将其设置为 0。

    注意:如果您的代码在包含为 document.addEventListener 之类的内容添加 polyfill 的第三方脚本的页面上运行,则对象检测可能会中断。在这种情况下,用户代理是最好的选择。


    检测浏览器是否是现代的

    如果您只对浏览器是否支持大多数 HTML 5 和 CSS 3 标准感兴趣,您可以reasonably assume IE 8 及更低版本仍然是主要问题应用程序。对window.getComputedStyle 的测试也将为您提供相当不错的现代浏览器组合(IE 9、FF 4、Chrome 11、Safari 5、Opera 11.5)。 IE 9 大大改进了标准支持,但原生 CSS 动画需要 IE 10。

    var isModernBrowser = ( !document.all || ( document.all && document.addEventListener ) ); 
    

    【讨论】:

    • “从用户代理获取 IE 版本”运行良好!只是为了确定,这将显示包括 IE11 在内的所有版本?
    • @omer 是的,因为它会查找字符串“MSIE”或“Trident”;后者由 IE 11 及更高版本使用。因此,它将适用于所有未来的 IE 版本,直到 MS 更改其浏览器引擎的名称。我相信新的 Edge 浏览器仍然使用 Trident。
    • 这很好用,谢谢@Beejor!我使用您的答案实现了一个简单的重定向到另一个页面:var ie = 0; try { ie = navigator.userAgent.match( /(MSIE |Trident.*rv[ :])([0-9]+)/ )[ 2 ]; } catch(e){} if (ie !== 0) { location.href = "../ie-redirect/redirect.html"; }
    • @BernardV 看起来不错!一个快速提示:如果您可以访问服务器,则在脚本中检测用户代理可能会更好,因为用户不会注意到任何重定向/闪烁、更少的 HTTP 请求等。但是在紧要关头用JS 也可以。
    【解决方案6】:

    Angular JS 就是这样做的。

    msie = parseInt((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]);
    if (isNaN(msie)) {
      msie = parseInt((/trident\/.*; rv:(\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]);
    }
    

    如果 IE 和 NaN 对于其他浏览器(如 chrome、firefox),msie 将为正数。

    为什么?

    从 Internet Explorer 11 开始,用户代理字符串发生了显着变化。

    参考这个:

    msdn #1 msdn #2

    【讨论】:

      【解决方案7】:

      解决方案:

      function GetIEVersion() {
        var sAgent = window.navigator.userAgent;
        var Idx = sAgent.indexOf("MSIE");
        // If IE, return version number.
        if (Idx > 0)
          return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));
      
        // If IE 11 then look for Updated user agent string.
        else if (!!navigator.userAgent.match(/Trident\/7\./))
          return 11;
      
        else
          return 0; //It is not IE
      
      }
      if ((GetIEVersion() > 0) || (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)){
        alert("This is IE " + GetIEVersion());
      }else {
        alert("This no is IE ");
      }		

      【讨论】:

      • 我最喜欢的 - 占 IE6-10 和 IE11。我也添加了检查边缘
      • 这会将 Firefox 检测为 This is IE 0
      【解决方案8】:

      我用的是更简单的方法:

      导航器全局对象有一个属性 touchpoints,在 Internet Exlorer 11 中称为 msMaxTouchPoints。

      所以如果你寻找:

      navigator.msMaxTouchPoints !== void 0 
      

      您将找到 Internet Explorer 11。

      【讨论】:

      • 它还在 IE 10 (Win 7) 上返回 trun
      【解决方案9】:
      var ua = navigator.userAgent.toString().toLowerCase();
      var match = /(trident)(?:.*rv:([\w.]+))?/.exec(ua) ||/(msie) ([\w.]+)/.exec(ua)||['',null,-1];
      var rv = match[2];
      return rv;
      

      【讨论】:

      • 如果您使用正则表达式进行检查,您可以添加 i 标志以使其不区分大小写,而不是 .toLowerCase()。也不需要 .toString() 方法。
      【解决方案10】:

      试试这个:

      var trident = !!navigator.userAgent.match(/Trident\/7.0/);
      var net = !!navigator.userAgent.match(/.NET4.0E/);
      var IE11 = trident && net
      var IEold = ( navigator.userAgent.match(/MSIE/i) ? true : false );
      if(IE11 || IEold){
      alert("IE")
      }else{
      alert("Other")
      }
      

      【讨论】:

      • 错误代码,因为 Acoo 浏览器在用户代理中使用“MSIE”。看useragentstring.com/pages/Acoo%20Browser
      • 错误的论点。我已经在所有 IE 浏览器上进行了测试,甚至包括 Win8 设备。
      • 您测试了 IE11 浏览器,但没有测试 Acoo 浏览器,并且 Acoo 浏览器在用户代理中使用“MSIE”,就像我说的那样,IEold 也将 Acoo 浏览器检测为 IEold(IE 的旧版本)并且我'确定 Acoo 浏览器在用户代理中使用“MSIE”,因为我已经使用 Acoo 浏览器在 javascript 测试站点上执行了 navigator.userAgent(测试站点:w3schools.com
      • 您能否为此提供更好的解决方案?
      • 你可以使用!navigator.userAgent.match("Acoo Browser;") && navigator.userAgent.match(/MSIE/i) ? true : false,但这并不总是有效,因为acoo浏览器并不总是有“Acoo Browser;”在它的用户代理中,但实际上你不需要关心 acoo 浏览器在它的用户代理中有“MSIE”,因为 acoo 浏览器几乎是一样的。
      【解决方案11】:

      这似乎是一个更好的方法。如果没有匹配,“indexOf”返回 -1。它不会覆盖主体上的现有类,只是添加它们。

      // add a class on the body ie IE 10/11
      var uA = navigator.userAgent;
      if(uA.indexOf('Trident') != -1 && uA.indexOf('rv:11') != -1){
          document.body.className = document.body.className+' ie11';
      }
      if(uA.indexOf('Trident') != -1 && uA.indexOf('MSIE 10.0') != -1){
          document.body.className = document.body.className+' ie10';
      }
      

      【讨论】:

        【解决方案12】:

        用这个检测大多数浏览器:

        var getBrowser = function(){
          var navigatorObj = navigator.appName,
              userAgentObj = navigator.userAgent,
              matchVersion;
          var match = userAgentObj.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
          if( match && (matchVersion = userAgentObj.match(/version\/([\.\d]+)/i)) !== null) match[2] = matchVersion[1];
          //mobile
          if (navigator.userAgent.match(/iPhone|Android|webOS|iPad/i)) {
            return match ? [match[1], match[2], mobile] : [navigatorObj, navigator.appVersion, mobile];
          }
          // web browser
          return match ? [match[1], match[2]] : [navigatorObj, navigator.appVersion, '-?'];
        };
        

        https://gist.github.com/earlonrails/5266945

        【讨论】:

          【解决方案13】:

          我在带有滚动条的元素上使用了onscroll 事件。在 IE 中触发时,我添加了以下验证:

          onscroll="if (document.activeElement==this) ignoreHideOptions()"
          

          【讨论】:

            【解决方案14】:

            仅适用于 IE 浏览器:

            var ie = 'NotIE'; //IE5-11, Edge+
                if( !!document.compatMode ) {
                    if( !("ActiveXObject" in window) ) ) ie = 'EDGE';
                    if( !!document.uniqueID){
                        if('ActiveXObject' in window && !window.createPopup ){ ie = 11; }
                        else if(!!document.all){
                                if(!!window.atob){ie = 10;}
                                else if(!!document.addEventListener) {ie = 9;}
                                else if(!!document.querySelector){ie = 8;}
                                else if(!!window.XMLHttpRequest){ie = 7;}
                                else if(!!document.compatMode){ie = 6;}
                                else ie = 5;
                            }
                    }
                }
            

            使用警报(即);

            测试:

            var browserVersionExplorer = (function() {
                var ie = '<s>NotIE</s>',
                    me = '<s>NotIE</s>';
            
                if (/msie\s|trident\/|edge\//i.test(window.navigator.userAgent) && !!(document.documentMode || document.uniqueID || window.ActiveXObject || window.MSInputMethodContext)) {
                        if (!!window.MSInputMethodContext) {
                            ie = !("ActiveXObject" in window) ? 'EDGE' : 11;
                        } else if (!!document.uniqueID) {
                            if (!!(window.ActiveXObject && document.all)) {
                                if (document.compatMode == "CSS1Compat" && !!window.DOMParser ) {
                                    ie = !!window.XMLHttpRequest ? 7 : 6;
                                } else {
                                    ie = !!(window.createPopup && document.getElementById) ? parseFloat('5.5') : 5;
                                }
                                if (!!document.documentMode && !!document.querySelector ) {
                                    ie = !!(window.atob && window.matchMedia) ? 10 : ( !!document.addEventListener ? 9 : 8);
                                }
                            } else ie = !!document.all ? 4 : (!!window.navigator ? 3 : 2);
                        }
                    }
                    
                return ie > 1 ? 'IE ' + ie : ie;
            })();
            
             alert(browserVersionExplorer);

            Update 01 Jun 2017

            现在我们可以使用更简单的东西了:

            var uA = window.navigator.userAgent,
                onlyIEorEdge = /msie\s|trident\/|edge\//i.test(uA) && !!( document.uniqueID || window.MSInputMethodContext),
                checkVersion = (onlyIEorEdge && +(/(edge\/|rv:|msie\s)([\d.]+)/i.exec(uA)[2])) || NaN;
            

            【讨论】:

            • 在哪里可以找到添加到新版本 Edge 中的新标准全局对象?我推断 Math.acosh 就是其中之一。
            • @j4v1 Math.acosh 仅在 Microsoft Edge(Edge 浏览器)中受支持。参考:msdn.microsoft.com/en-us/en-en/library/dn858239(v=vs.94).aspx
            • 这种方法对我不起作用。过去它正确检测到 IE11,但现在我在 Windows 10 Enterprise(版本 1607,OS Build 14393.1198)上运行的 Internet Explorer 版本 11.1198.14393.0(更新版本 11.0.42 (KB4018271))数学似乎支持 acosh 方法。
            • @Thijs 在带有 IE11 v 11.1198.14393.0 的 Windows 10 教育版中,我测试成功。你应该根据 ES6 尝试另一个数学函数。
            • @JamesPeter 我已经检查了 document.documentMode。这似乎是检查 IE11 或 Edge 的更可靠的属性。 documentMode 在 IE11 中存在,但在 Edge 中不再存在。
            【解决方案15】:

            坦率地说,我会说使用一个可以满足您需求的库(例如 platform.js)。在某些时候情况会发生变化,并且库将为这些变化配备,使用正则表达式的手动解析将失败。

            感谢上帝 IE 消失了...

            【讨论】:

              【解决方案16】:

              使用DetectOS.js。这是一个针对流行操作系统和浏览器的简单 JS 定义,无需依赖:

              class DetectOS {
                  constructor() {
                      this.browser = this.searchString(this.dataBrowser())
                      this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion)
                      this.OS = this.searchString(this.dataOS())
                  }
              
                  searchString(data) {
                      for (let i = 0; i < data.length; i++) {
                          let
                              dataString = data[i].string,
                              dataProp = data[i].prop
                          this.versionSearchString = data[i].versionSearch || data[i].identity
                          if (dataString) {
                              if (dataString.indexOf(data[i].subString) !== -1) {
                                  return data[i].identity
                              }
                          } else if (dataProp) {
                              return data[i].identity
                          }
                      }
                  }
              
                  searchVersion(dataString) {
                      let index = dataString.indexOf(this.versionSearchString)
                      if (index === -1) return
                      return parseFloat(dataString.substring(index+this.versionSearchString.length + 1))
                  }
              
                  dataBrowser() {
                      return [
                          /***************
                           * Chrome
                           ***************/
                          {
                              string: navigator.userAgent,
                              subString: "Chrome",
                              identity: "Chrome"
                          },
                          /***************
                           * Safari
                           ***************/
                          {
                              string: navigator.vendor,
                              subString: "Apple",
                              identity: "Safari",
                              versionSearch: "Version"
                          },
                          /***************
                           * For Older Opera (12.18-)
                           ***************/
                          {
                              prop: window.opera,
                              identity: "Opera",
                              versionSearch: "Version"
                          },
                          /***************
                           * Internet Explorer 10
                           ***************/
                          {
                              string: navigator.userAgent,
                              subString: "MSIE",
                              identity: "IE10",
                              versionSearch: "MSIE"
                          },
                          /***************
                           * Internet Explorer 11
                           ***************/
                          {
                              string: navigator.userAgent,
                              subString: "Trident",
                              identity: "IE11",
                              versionSearch: "rv"
                          },
                          /***************
                           * Edge
                           ***************/
                          {
                              string: navigator.userAgent,
                              subString: "Edge",
                              identity: "Edge",
                              versionSearch: "Edge"
                          },
                          /***************
                           * Firefox
                           ***************/
                          {
                              string: navigator.userAgent,
                              subString: "Firefox",
                              identity: "Firefox"
                          },
                          {
                              string: navigator.userAgent,
                              subString: "Gecko",
                              identity: "Mozilla",
                              versionSearch: "rv"
                          },
                          /***************
                           * For Older Netscapes (4-)
                           ***************/
                          {
                              string: navigator.userAgent,
                              subString: "Mozilla",
                              identity: "Netscape",
                              versionSearch: "Mozilla"
                          },
                          /***************
                           * For Newer Netscapes (6+)
                           ***************/
                          {
                              string: navigator.userAgent,
                              subString: "Netscape",
                              identity: "Netscape"
                          },
                          /***************
                           * Other Browsers
                           ***************/
                          {
                              string: navigator.userAgent,
                              subString: "OmniWeb",
                              versionSearch: "OmniWeb/",
                              identity: "OmniWeb"
                          },
                          {
                              string: navigator.vendor,
                              subString: "iCab",
                              identity: "iCab"
                          },
                          {
                              string: navigator.vendor,
                              subString: "KDE",
                              identity: "Konqueror"
                          },
                          {
                              string: navigator.vendor,
                              subString: "Camino",
                              identity: "Camino"
                          }
                      ]
                  }
              
                  dataOS() {
                      return [
                          {
                              string: navigator.platform,
                              subString: 'Win',
                              identity: 'Windows'
                          },
                          {
                              string: navigator.platform,
                              subString: 'Mac',
                              identity: 'macOS'
                          },
                          {
                              string: navigator.userAgent,
                              subString: 'iPhone',
                              identity: 'iOS'
                          },
                          {
                              string: navigator.userAgent,
                              subString: 'iPad',
                              identity: 'iOS'
                          },
                          {
                              string: navigator.userAgent,
                              subString: 'iPod',
                              identity: 'iOS'
                          },
                          {
                              string: navigator.userAgent,
                              subString: 'Android',
                              identity: 'Android'
                          },
                          {
                              string: navigator.platform,
                              subString: 'Linux',
                              identity: 'Linux'
                          }
                      ]
                  }
              }
              
              const Detect = new DetectOS()
              
              console.log("We know your browser – it's " + Detect.browser + " " + Detect.version);
              console.log("We know your OS – it's " + Detect.OS);
              console.log("We know everything about you.");

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2013-12-04
                • 1970-01-01
                • 2016-04-20
                • 2013-09-25
                • 2014-08-07
                • 2014-01-12
                • 2014-02-24
                • 1970-01-01
                相关资源
                最近更新 更多