检查用户是否正在使用IE浏览器

490

我会通过点击具有特定类的div来调用以下类似的函数。

是否有一种方法可以在启动函数时检查用户是否正在使用Internet Explorer,并在他们使用其他浏览器时中止/取消它,以便它仅适用于IE用户?这里的用户都将在IE8或更高版本上运行,因此我不需要覆盖IE7和更低版本。

如果我能知道他们正在使用哪个浏览器,那就太好了,但并非必需。

示例函数:

$('.myClass').on('click', function(event)
{
    // my function
});

7
按照现代Web开发标准,开发旧版IE的做法是不好的。 - Rosseyn
11
实际上,这种“不良做法”是由标准本身强制实施的,所以这不是开发者的错......浏览器的工作方式不同,规范对实现问题过于宽松。为了做出既不会有漏洞又不会无聊透顶的东西,必须进行浏览器检测。我建议采用另一种最佳实践:随着现代Web开发的发展,支持非基于Chromium的浏览器是一种不良做法(其中Safari被认为根本不是基于Chromium的)。很抱歉,但这种疯狂必须在某个时候以某种方式结束...... - user2173353
4
现今最好的实践是使用“特性检测”而非“浏览器检测”。询问所需功能是否由浏览器提供即可。 - Chris Rogers
2
@Chris - 抱歉...我的本意是想让那句话更有幽默感。我要把责任归咎于IE窃取了我的快乐,留下了苦涩和沮丧。 :) - JDB
2
@JDB - 完全不用担心。IE浏览器(又称“欢乐的月亮面孔杀手”)已经扼杀了许多人的灵魂。 :-) - Chris Rogers
显示剩余9条评论
33个回答

726

几年过去了,Edge浏览器现在使用Chromium作为其渲染引擎。
遗憾的是,仍然需要检查IE 11。

以下是更直接的方法,因为古老版本的IE应该已经消失了。

if (window.document.documentMode) {
  // Do IE stuff
}

这是我的旧答案(2014):

在Edge浏览器中,用户代理字符串已经改变了。


/**
 * detect IEEdge
 * returns version of IE/Edge or false, if browser is not a Microsoft browser
 */
function detectIEEdge() {
    var ua = window.navigator.userAgent;

    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }

    var trident = ua.indexOf('Trident/');
    if (trident > 0) {
        // IE 11 => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }

    var edge = ua.indexOf('Edge/');
    if (edge > 0) {
       // Edge => return version number
       return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }

    // other browser
    return false;
}

示例用法:

alert('IEEdge ' + detectIEEdge());

IE 10 的默认字符串:

Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)

IE 11的默认字符串:

Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko 

Edge 12 的默认字符串:

Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0 

Edge 13 的默认字符串(感谢 @DrCord):

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586 

Edge 14 的默认字符串:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/14.14300 

Edge 15 的默认字符串:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063 

Edge 16的默认字符串:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299 

Edge 17 的默认字符串:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134 

Edge 18(Insider preview)的默认字符串:

Mozilla/5.0 (Windows NT 10.0; Win64; x64; ServiceUI 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17730 

CodePen测试:

http://codepen.io/gapcode/pen/vEJNZN


4
谢谢您的评论。我还没有验证您的答案,但我想评论一件事:由于第一个“if”包含了一个“return”,所以之后不需要再加上“else”。 - Mario
33
为什么新版IE会更改用户代理行?我很好奇。微软是不是真的不希望我们检测到他们糟糕的网络浏览器? - c00000fd
3
@SameerAlibhai 理论上听起来不错,但在实践中,特别是当前情况下,这并不实用。有时会出现一些问题,单个“功能”检测无法涵盖,并且某些功能具有实现怪癖,只能通过了解浏览器来解决。如果我想做一些简单的事情,比如收集浏览器统计信息,该怎么办? - Slight
34
需要注意的是,Edge并不是真正的“IE12”,而实际上是一个完全独立的浏览器。Windows 10安装了IE11和Edge两个浏览器。 - moloko
3
Edge 不是 Internet Explorer 或 IE12,请停止暗示它们之间的关系。此外,检测 Edge 有什么意义?它基于 Chromium,因此您应该将 Opera 和 Chrome 也加入到这段代码中。 - hda
显示剩余22条评论

529

使用以下 JavaScript 方法:

function msieversion() 
{
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0) // If Internet Explorer, return version number
    {
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    }
    else  // If another browser, return 0
    {
        alert('otherbrowser');
    }

    return false;
}

您可以在以下的Microsoft支持网站上找到详细信息:

如何通过脚本确定浏览器版本

更新: (IE 11 支持)

function msieversion() {

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer, return version number
    {
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    }
    else  // If another browser, return 0
    {
        alert('otherbrowser');
    }

    return false;
}

31
虽然这将作为ua变量永远不会以MSIE开头而运行良好,但编写if (msie > 0)是具有误导性的。如果未找到该值,则indexOf()函数返回-1而不是0。因此,if (msie > -1)更能解释清楚。 - Neville Nazerane
67
对我来说,在IE11中这会返回NaN。 - verism
8
@verism 和其他人:请查看这个答案,它也适用于 IE 11:https://dev59.com/MGIj5IYBdhLWcg3wrG8q#21712356 - Leniel Maccaferri
9
navigator.userAgent.indexOf("MSIE ") > 0 || navigator.userAgent.indexOf("Trident") > 0 || navigator.userAgent.indexOf("Edge") > 0这段代码的意思是:如果用户代理字符串中包含"MSIE "、"Trident"或"Edge",则返回值为真。 - tylermauthe
15
/Edge\/|Trident\/|MSIE /.test(window.navigator.userAgent) 这段代码可以在 IE10 和 IE11 上运作。如果您能验证是否适用于 IE9 及以下版本和 Edge 浏览器,请编辑答案。 - Indolering
显示剩余13条评论

166

如果您只想知道浏览器是否为IE,可以这样做:

var isIE = false;
var ua = window.navigator.userAgent;
var old_ie = ua.indexOf('MSIE ');
var new_ie = ua.indexOf('Trident/');

if ((old_ie > -1) || (new_ie > -1)) {
    isIE = true;
}

if ( isIE ) {
    //IE specific code goes here
}

更新1:更好的方法

我现在推荐这个方法。它仍然很易读,而且代码量要少得多 :)

var ua = window.navigator.userAgent;
var isIE = /MSIE|Trident/.test(ua);

if ( isIE ) {
  //IE specific code goes here
}

更新2:CSS中的IE测试

首先,如果可以的话,应该使用@supports语句而不是JS来检查浏览器是否支持某个CSS特性。

感谢评论区的JohnnyFun提供缩短版答案 :)

.element {
  /* styles for all browsers */
}

@supports (display: grid) {
  .element {
    /* styles for browsers that support display: grid */
  }
}

(请注意,IE完全不支持@supports,并将忽略放置在@supports语句中的任何样式。)
如果使用@supports无法解决问题,则可以执行以下操作:
// JS

var ua = window.navigator.userAgent;
var isIE = /MSIE|Trident/.test(ua);

if ( isIE ) {
  document.documentElement.classList.add('ie')
}

/* CSS */

.element {
  /* styles that apply everywhere */
}

.ie .element {
  /* styles that only apply in IE */
}

(注:classList 在JavaScript中相对较新,我认为除了IE11外,在IE浏览器中不起作用。可能也适用于IE10。)
如果您在项目中使用SCSS(Sass),则可以简化为:
/* SCSS (Sass) */

.element {
  /* styles that apply everywhere */

  .ie & {
    /* styles that only apply in IE */
  }
}

更新 3:添加微软 Edge(不建议)

如果您也想将微软 Edge 添加到列表中,可以按照以下步骤进行操作。然而,我不建议这样做,因为 Edge 是一款比 IE 更强大的浏览器。

var ua = window.navigator.userAgent;
var isIE = /MSIE|Trident|Edge\//.test(ua);

if ( isIE ) {
  //IE & Edge specific code goes here
}

6
或者用更少的字节表示相同意思: ms_ie = ~ua.indexOf('MSIE ') || ~ua.indexOf('Trident/'); ;-) (此代码片段可能是检查浏览器是否为Internet Explorer的一部分。如果ua字符串中包含“MSIE”或“Trident /”,则将ms_ie设置为true,否则设置为false。最后的笑脸是注释或幽默) - Simon Steinberger
12
我的版本对于人类来说更加直观易懂,但是少一些字节总是好的 :) - Daniel Tonon
7
或者 ms_ie = !!ua.match(/MSIE|Trident/) (该代码片段用于检查用户代理字符串中是否包含“MSIE”或“Trident”,并将结果存储在名为“ms_ie”的变量中,该变量的值为布尔类型。) - xori
6
或者 ms_ie = /MSIE|Trident/.test(ua) 该句代码用于检测用户使用的浏览器是否为 Internet Explorer(IE),它采用了正则表达式来测试该字符串中是否存在“MSIE”或“Trident”,如果存在,则返回 true,否则返回 false。 - JohnnyFun
1
一个组件需要检查IE。 import isIE from './isIE.js'。现在另一个组件出于某种原因需要检查IE,import isIE from './isIE.js'。如果这还不足以说服您,那么它对于可读性来说更好。使用变量有两个原因:减少代码重复;澄清代码的含义。当您阅读 if (/MSIE|Trident/.test(window.navigator.userAgent)) 时,与 if (isIE) 相比,它要不那么明显。 - Daniel Tonon
显示剩余6条评论

49

此代码适用于任何版本的Internet Explorer,其返回值为true

function isIE(userAgent) {
  userAgent = userAgent || navigator.userAgent;
  return userAgent.indexOf("MSIE ") > -1 || userAgent.indexOf("Trident/") > -1 || userAgent.indexOf("Edge/") > -1;
}

参数userAgent是可选的,默认为浏览器的用户代理。


这个应该是没问题的,但你基本上忘了为IE浏览器设置一个默认的“return true”或“return 1”的值。当检测到IE浏览器时,当前并没有返回任何值。 - Vincent Edward Gedaria Binua
14
为什么要把 Edge 当作 IE 来处理?就兼容性而言,现在它们几乎没有任何共同之处。 - minexew
1
@docta_faustus userAgent是一个参数,而不是全局变量。 - bendytree

34
你可以使用navigator对象来检测用户导航器,不需要使用jQuery,下面的4个注释已经包含在内,因此该代码段按预期工作。
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent) || navigator.userAgent.indexOf("Trident/") > -1 ){ 
 // Do stuff with Internet-Exploders ... :)
}

http://www.javascriptkit.com/javatutors/navigator.shtml


4
这让我的IE11出现了虚假的结果。 - Curtis
2
IE11的用户代理与MSIE(X.X)不同;通过检查Trident即可找到IE11。 - Orpheus
这在Firefox 45.0.2中会产生误报。 - Tim S. Van Haren
错误的测试indexOf函数不像正则表达式的test函数一样返回true或false。你需要使用navigator.userAgent.indexOf("Trident/") != -1。 - Dahar Youssef

32

以下是 AngularJS 团队的实现方式(版本 1.6.5):

var msie, // holds major version number for IE, or NaN if UA is not IE.

// Support: IE 9-11 only
/**
 * documentMode is an IE-only property
 * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
 */
msie = window.document.documentMode;

然后散布在代码中有几行使用它作为数字的代码,例如

if (event === 'input' && msie <= 11) return false;

if (enabled && msie < 8) {

在 MS Edge 中,window.document.documentMode 未定义。 - Veselin Vasilev
28
因为 MS Edge 不是 IE,所以它在 MS Edge 中未定义! - JCKödel
2
document.documentMode 支持 IE8+。对于 Edge 或 Chrome/FireFox,它将返回 'undefined'... 我将此代码更改为 var IEver = window.document.documentMode || (window.attachEvent? 1 : 99);,以便在 IE8+ 中返回确切的 IE 版本,对于非 IE 浏览器返回 99(通常是现代浏览器),而对于旧版 IE5-7 返回 1。这样编写是因为我们通常只需要为一些旧版 IE 进行特殊处理。所以,如果 (IEver < 9),则表示它是旧版 IE。 - S.Serpooshan

19

你可以简单地这样做:

var isIE = window.document.documentMode ? true : false; // this variable will hold if the current browser is IE
我知道这个问题很老,但是如果有人滚动到那里,他们可以看到简单的答案 :)
我知道这个问题很老,但是如果有人滚动到那里,他们可以看到简单的答案 :)

11

方法 01:
$.browser 已在 jQuery 1.3 版本中被弃用并在 1.9 版本中移除。

if ( $.browser.msie) {
  alert( "Hello! This is IE." );
}

方法 02:
使用条件注释

<!--[if gte IE 8]>
<p>You're using a recent version of Internet Explorer.</p>
<![endif]-->

<!--[if lt IE 7]>
<p>Hm. You should upgrade your copy of Internet Explorer.</p>
<![endif]-->

<![if !IE]>
<p>You're not using Internet Explorer.</p>
<![endif]>

方法03:

 /**
 * Returns the version of Internet Explorer or a -1
 * (indicating the use of another browser).
 */
function getInternetExplorerVersion()
{
    var rv = -1; // Return value assumes failure.

    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var ua = navigator.userAgent;
        var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat( RegExp.$1 );
    }

    return rv;
}

function checkVersion()
{
    var msg = "You're not using Internet Explorer.";
    var ver = getInternetExplorerVersion();

    if ( ver > -1 )
    {
        if ( ver >= 8.0 ) 
            msg = "You're using a recent copy of Internet Explorer."
        else
            msg = "You should upgrade your copy of Internet Explorer.";
    }

    alert( msg );
}

方法04:
使用JavaScript / 手动检测

/*
     Internet Explorer sniffer code to add class to body tag for IE version.
     Can be removed if your using something like Modernizr.
 */
 var ie = (function ()
 {

     var undef,
     v = 3,
         div = document.createElement('div'),
         all = div.getElementsByTagName('i');

     while (
     div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i>< ![endif]-->',
     all[0]);

     //append class to body for use with browser support
     if (v > 4)
     {
         $('body').addClass('ie' + v);
     }

 }());

参考链接


@radhe,我已经更新了答案,希望这对你有用。 - Aamir Shahzad
作为注意事项:方法2 在标准模式下将无法在IE10及更高版本中正常工作。更多信息请参见:不再支持条件注释 - insertusernamehere
@insertusernamehere,你说得非常正确。如果你只是针对IE10进行一些CSS修复,那么使用.ie10类是最好的选择之一。因为Internet Explorer 10会在HTML元素<html class="ie10">中添加".ie10"类,所以你可以像这样使用它:.ie10 .myclass {//some css here} - Aamir Shahzad

11

利用上述答案,简洁明了地返回布尔值:

var isIE = /(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent);


1
在Windows 10上的FireFox 44.0.2中返回false。@SiKni8,哪个版本的FireFox返回true? - Arthur Hebert-Ryan

9

我只是想检查一下浏览器是否为IE11或更早版本,因为它们很差劲。

function isCrappyIE() {
    var ua = window.navigator.userAgent;
    var crappyIE = false;
    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {// IE 10 or older => return version number        
        crappyIE = true;
    }
    var trident = ua.indexOf('Trident/');
    if (trident > 0) {// IE 11 => return version number        
        crappyIE = true;
    }
    return crappyIE;
}   

if(!isCrappyIE()){console.table('not a crappy browser);}

3
这让我支持它对命名规范标准的高度重视。 - redbandit

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