【问题标题】:How to detect Internet Explorer 11 and below versions?如何检测 Internet Explorer 11 及以下版本?
【发布时间】:2018-04-23 17:24:43
【问题描述】:

我想知道如何检测查看我网站的用户是否使用 Internet Explorer 11 或更低版本的 Javascript。

它应该兼容并适用于所有这些版本。

如何实现?

【问题讨论】:

  • 如果string Tridentwindow.navigator.userAgent 中。
  • @AjAX。 Trident 仅适用于 IE11,旧版 IE 使用 MSIE
  • @RyanWilson 不。它不是。 Trident 归结为 IE 6。两者都是。
  • @AjAX 好的。不知道两者都在 IE6 中,但最好还是检查一下两者,以防某些旧计算机运行比 IE6 更旧的版本。
  • @DerekBrown ,这是不正确的,因为我不想只检测版本 11 ,我得到了答案,所以谢谢

标签: javascript internet-explorer


【解决方案1】:

给你,这应该适合你:

//Per Icycool, one liner
//function isIE(){
//                 return window.navigator.userAgent.match(/(MSIE|Trident)/);
//               }

function isIE() {
    const ua = window.navigator.userAgent; //Check the userAgent property of the window.navigator object
    const msie = ua.indexOf('MSIE '); // IE 10 or older
    const trident = ua.indexOf('Trident/'); //IE 11
    
    return (msie > 0 || trident > 0);
}


//function to show alert if it's IE
function ShowIEAlert(){
    if(isIE()){
       alert("User is using IE");
    }
}

【讨论】:

  • window.navigator.userAgent.match(/(MSIE|Trident)/) 如果你想在 1 行中完成
  • @Timm uhm 只是使用字符串模式的旧习惯,以防正则表达式中有其他部分。在这种情况下,您是对的,不需要括号。
  • 如果你想兼容旧版本的IE,请使用var而不是const
  • 非常感谢。拯救了我的一天
  • @Siva-Dev-Wizard 不客气。很高兴帮助:)
【解决方案2】:

检查 documentmode - IE 唯一属性:

if (document.documentMode) 
    alert('this is IE');

【讨论】:

    【解决方案3】:

    我想简化正确答案。这将返回 truefalse

    function is_IE() {
      return (window.navigator.userAgent.match(/MSIE|Trident/) !== null);
    }
    

    【讨论】:

      【解决方案4】:

      更简单的版本,返回布尔值

      function isIE() {
        return !!window.navigator.userAgent.match(/MSIE|Trident/);
      }
      

      【讨论】:

      • 仅供参考 /MSIE|Trident/.test(window.navigator.userAgent) 返回布尔值。
      猜你喜欢
      • 2015-05-29
      • 2019-11-20
      • 1970-01-01
      • 2023-03-25
      • 2016-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多