繁体   English   中英

JavaScript:检测 IE 的最佳方式

[英]JavaScript: The best way to detect IE

阅读这篇文章,我发现了以下一段代码:

if ('v'=='\v') { // Note: IE listens on document
    document.attachEvent('onstorage', onStorage, false);
}

这种方法'v'=='\\v'是个好主意吗? 这是有史以来检测 IE 的最短方法吗?

如果可以避免,请不要测试浏览器。 做特征检测。 这意味着您的代码(更有可能)是面向未来的。 在这种情况下,例如,如果您发现浏览器是 IE 并因此决定使用attachEvent ,您将错过addEventListener (superior) 在 IE9 中可用的事实。

在这种情况下,请测试以查看document.addEventListener存在。 如果是这样,你就有了答案。

if (document.addEventListener) {
    document.addEventListener(...);
} else {
    document.attachEvent(...);
}

编辑:duri 上面的评论表明该测试在 IE9 中失败(按照标准),这实际上意味着它是addEventListener的完美测试,因为它可以从 IE9 获得。 然而,为特定功能而不是特定浏览器进行编程仍然要好得多。

您可以通过以下方式检查 IE 的引擎 Trident:

var trident = !!window.ActiveXObject;

正如MSDN 上所述,它仅在 IE 中受支持。

编辑:

注意:上面的代码在 IE-11 中返回 false,如果您还想检测 IE-11,请使用以下代码:

var isIE = "ActiveXObject" in window; //window.ActiveXObject !== undefined;

要检查浏览器是否为 Internet Explorer,请使用功能检测来检查documentMode

http://msdn.microsoft.com/en-us/library/ie/cc196988%28v=vs.85%29.aspx

此代码检查浏览器是否为 Internet Explorer 8、9、10 或 11:

var docMode = document.documentMode,
    hasDocumentMode = (docMode !== undefined), 
    isIE8 = (docMode === 8),
    isIE9 = (docMode === 9),
    isIE10 = (docMode === 10),
    isIE11 = (docMode === 11),
    isMsEdge = window.navigator.userAgent.indexOf("Edge/") > -1;

// browser is IE
if(hasDocumentMode) {
     if(isIE11){
         // browser is IE11
     } else if(isIE10){
         // browser is IE10
     } else if(isIE9){
         // browser is IE9
     } else if(isIE8){
         // browser is IE8
     }
} else {
   // document.documentMode is deprecated in MS Edge
   if(isMsEdge){
         // browser is MS Edge
   }
}

检查document.documentMode只能在 IE8 到 IE11 中工作,因为documentMode是在 IE8 中添加的,并且在 MS Edge 中已被弃用/删除。

http://msdn.microsoft.com/en-us/library/ff406036%28v=vs.85%29.aspx

我希望这有帮助!

更新

如果您确实需要检测 IE7,请检查document.attachEvent

var isIE7 = (document.attachEvent !== undefined);
if(isIE7) {
      // browser is IE7
}

IE7 返回一个对象,但如果浏览器是 IE11(例如),那么这将返回为undefined ,因为 IE11 没有attachEvent

更新:

添加了对 MS Edge 的检查。 document.documentMode 在 MS Edge弃用 由于 MS Edge 的性质,您可以在用户代理中检查Edge/ Microsoft 使在 MS Edge 中使用功能检测变得困难。

IE11 及更早版本不支持 JavaScript contains includes()方法。 所以可以通过代码来检查是否支持includes()方法。 这适用于所有版本的 IE。 但是包含方法不适用于早期版本的 Chrome、Firefox、Safari 和 Opera。 这可能不是检测 IE 的最有效方法。

 var aString = "something"; if(!aString.includes){ alert("You are using IE"); } else { alert("You are not using IE"); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM