[removed] The best way to detect IE

前端 未结 3 1039
礼貌的吻别
礼貌的吻别 2021-01-13 12:22

Reading this article I\'ve found a following piece of code:

if (\'v\'==\'\\v\') { // Note: IE listens on document
    document.attachEvent(\'onstorage\', onS         


        
3条回答
  •  长情又很酷
    2021-01-13 13:03

    To check if the browser is Internet Explorer, use feature detection to check for documentMode:

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

    This code checks to see if the browser is Internet Explorer 8, 9, 10, or 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
       }
    }
    

    Checking document.documentMode will only work in IE8 through IE11, since documentMode was added in IE8 and has been deprecated / removed in MS Edge.

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

    I hope this helps!

    UPDATE

    If you really need to detect IE7, check for document.attachEvent:

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

    IE7 returns a object, but if the browser is IE11 (for example), then this would come back as undefined, since IE11 does not have attachEvent.

    UPDATE:

    Added check for MS Edge. document.documentMode was deprecated in MS Edge. Due to the nature of MS Edge, you can check for Edge/ in the User Agent. Microsoft is making it difficult to use feature detection in MS Edge.

提交回复
热议问题