如何检测Internet Explorer 11及以下版本?

23

我想知道如何使用Javascript检测用户是否使用Internet Explorer 11或以下版本。

它应该与所有这些版本兼容并且可以正常工作。

如何实现这一点?


如果string Tridentwindow.navigator.userAgent中。 - deEr.
@AjAX。Trident 只适用于 IE11,早期版本的 IE 使用 MSIE。 - Ryan Wilson
@RyanWilson 不是这样的。TridentIE 6 开始就存在了。两者都是。 - deEr.
@AjAX 好的。我不知道两者都存在于IE6中,但最好检查两者,以防一些古老的计算机运行比IE6更旧的版本。 - Ryan Wilson
1
@DerekBrown,不对,因为我不只是想检测版本11,但我已经得到答案了,谢谢。 - user9678848
4个回答

47

这是给你的,应该可以为你工作:

//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");
    }
}

22
如果你想在一行中完成,可以这样写:window.navigator.userAgent.match(/(MSIE|Trident)/)。这段代码用于检测浏览器是否是 Internet Explorer 或 Microsoft Edge(使用 Trident 引擎)。 - Icycool
1
@Timm 嗯,只是习惯性地在字符串模式中使用括号,以防正则表达式中还有其他部分。在这种情况下,你是正确的,括号是不必要的。 - Icycool
1
如果您想要与较旧版本的IE兼容,请使用var而不是const - Roland Pihlakas
1
非常感谢,你救了我的一天。 - Siva-Dev-Wizard
1
@Siva-Dev-Wizard 不用谢。很高兴能帮到你 :) - Ryan Wilson
显示剩余4条评论

9

检查 documentmode - 仅适用于IE的属性:

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

8

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

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

1

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

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

3
FYI /MSIE|Trident/.test(window.navigator.userAgent) 返回一个布尔值。 - Steve Clay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接