簡體   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