如何正确检测IE11或更高版本?

How to properly detect IE11 or later?

我正在 运行使用 IE 11 安装 Windows 7(64 位)

具有以下navigator.userAgent

"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; SLCC2;
.NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0;
.NET4.0C; .NET4.0E)"

我希望能够在我的站点上显示任何内容之前检测到 IE 的版本。换句话说,我所在的公司已经将大部分计算机更新为 运行 IE11 或 Chrome。但是有些电脑还有IE9.

我希望我的网站能够为 运行使用 IE11 或 chrome 的人正常工作。应该检测到任何其他版本的浏览器,并通知用户更新他的机器。

我在 SO 上找到的所有代码都引用 v11 作为 userAgent 字符串的一部分,但这里不是这种情况。

编辑:我也尝试过:

var isIE11 = !!(navigator.userAgent.match(/Trident/) 
             && !navigator.userAgent.match(/MSIE/));  
         //value is false in IE6/IE9/IE11

var isIE11 = !!(navigator.userAgent.match(/Trident/) 
                 && navigator.userAgent.match(/rv 11/));   
          //value is false in IE6/IE9/IE11

var isIE11 = !(window.ActiveXObject) && "ActiveXObject" in window;
           //value is false in IE6/IE9/IE11

如何检测IE11?

编辑 2:此 link http://kangax.github.io/compat-table/es6/ 有一种方法可以检查 hoisted ... 仅在 IE11 上有 运行 的功能。所以我也试过这个:

{ function f() { return 1; } }
  function g() { return 1; }
{ function g() { return 2; } }
{ function h() { return 1; } }
  function h() { return 2; }

alert( f() === 1 && g() === 2 && h() === 1);  // alerts false in all ie versions

这 returns 仅在 IE11 中为真:

!(window.ActiveXObject) && "ActiveXObject" in window

检查Trident引擎版本为7.0;较早版本的 Internet Explorer 具有较早的 Trident 引擎版本。

示例:

  • Internet Explorer 10 有 Trident 6.0
  • Internet Explorer 9 有 Trident 5.0

来源:https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx

请注意,您必须特别注意非桌面 PC Internet Explorer 版本(Lumia 手机、Xbox 等)。

此外,Microsoft 浏览器的最新版本 Edge 不再使用 Trident 版本。

如果只有 IE 浏览器连接到该页面,则测试 hoisted block-level function declaration,因为仅在 IE11+

中受支持

function hoistTest() {
    // Note: only available outside of strict mode.
    { function f() { return 1; } }
      function g() { return 1; }
    { function g() { return 2; } }
    { function h() { return 1; } }
      function h() { return 2; }
    
    return f() === 1 && g() === 2 && h() === 1;
}

document.getElementById('out').appendChild(document.createTextNode('hoisted block-level function declaration: ' + hoistTest()));
<pre id="out"></pre>

更新:在 IE11 上运行的截图

在 IE 中,您可以在 document 上访问 documentMode 属性,这将 return IE 的版本。

要测试 11 和更大的数字,您可以使用以下内容:

document.documentMode > 10