代码之家  ›  专栏  ›  技术社区  ›  Marco Demaio

Javascript IE检测,为什么不使用简单的条件注释?

  •  47
  • Marco Demaio  · 技术社区  · 14 年前

    为了检测IE,大多数Javascript库都会使用各种技巧。

    • jQuery似乎在页面的DOM中添加了一个临时对象来检测一些特性,
    • YUI2在 YAHOO.env.ua = function() (文件 yahoo.js )

    阅读后 this answer 我想这是真的,为了简单地检测Javascript中的IE,我们可以简单地添加到页面中:

    <!--[if IE]><script type="text/javascript">window['isIE'] = true;</script><![endif]-->
    
    <script type="text/javascript" src="all-your-other-scripts-here.js"></script>
    

    现在 window.isIE 变量是为所有Javascript代码设置的,只需执行以下操作:

    if(window.isIE)
       ...
    

    除此之外,这可能会导致痛苦,因为它必须添加到所有页面中, 有没有什么我可能不知道的问题/考虑?


    仅供参考:我知道最好使用 object detection rather than browser detection ,但在某些情况下,仍需要使用浏览器检测。

    15 回复  |  直到 7 年前
        1
  •  58
  •   Marcel Korpel    14 年前

    詹姆斯·帕多尔西 little snippet on GitHub 我在这里引用:

    // ----------------------------------------------------------
    // A short snippet for detecting versions of IE in JavaScript
    // without resorting to user-agent sniffing
    // ----------------------------------------------------------
    // If you're not in IE (or IE version is less than 5) then:
    // ie === undefined
    // If you're in IE (>=5) then you can determine which version:
    // ie === 7; // IE7
    // Thus, to detect IE:
    // if (ie) {}
    // And to detect the version:
    // ie === 6 // IE6
    // ie > 7 // IE8, IE9 ...
    // ie < 9 // Anything less than IE9
    // ----------------------------------------------------------
    
    // UPDATE: Now using Live NodeList idea from @jdalton
    
    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]
        );
    
        return v > 4 ? v : undef;
    
    }());
    

    当然,所有的学分都应该交给詹姆斯,我只是信使(但请拍摄信使,如果我的复制粘贴操作出错)。

    还要看看创造的叉子。Paul Irish在 comment .

        2
  •  39
  •   AlfonsoML    14 年前

    如果您想这样做,我认为最好使用条件编译,因为您可以在javascript中进行编译,而无需更改html:

    var isIE = /*@cc_on!@*/false;
    
        3
  •  26
  •   Sean Colombo    10 年前

    Marcel Korpel的答案不再有效(在IE 10中,它返回undef,因此IE 10看起来不是IE)。注:现在更新为与IE 11一起工作。

    这是代码的变体,但是它来自 Microsoft's recommendations . 如果您使用的是前面的代码,您可以直接插入这个替换项,因为它是以完全相同的方式被调用的。

    与条件注释/编译不同,它还应该可以使用最小化的方法。

    // ----------------------------------------------------------
    // If you're not in IE (or IE version is less than 5) then:
    // ie === undefined
    // If you're in IE (>=5) then you can determine which version:
    // ie === 7; // IE7
    // Thus, to detect IE:
    // if (ie) {}
    // And to detect the version:
    // ie === 6 // IE6
    // ie > 7 // IE8, IE9, IE10 ...
    // ie < 9 // Anything less than IE9
    // ----------------------------------------------------------
    var ie = (function(){
        var undef,rv = -1; // Return value assumes failure.
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf('MSIE ');
        var trident = ua.indexOf('Trident/');
    
        if (msie > 0) {
            // IE 10 or older => return version number
            rv = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
        } else if (trident > 0) {
            // IE 11 (or newer) => return version number
            var rvNum = ua.indexOf('rv:');
            rv = parseInt(ua.substring(rvNum + 3, ua.indexOf('.', rvNum)), 10);
        }
    
        return ((rv > -1) ? rv : undef);
    }());
    

    更新为与IE11一起工作。感谢'acarlon'指出它不起作用,和'mario'的代码,我的基础上修复!

        4
  •  11
  •   webber55    11 年前

    IE11已经改变了很多,现在很多过去的浏览器检测方法都不起作用。下面的代码适用于IE11及更早版本。

    function isIE()
    {
        var isIE11 = navigator.userAgent.indexOf(".NET CLR") > -1;      
        var isIE11orLess = isIE11 || navigator.appVersion.indexOf("MSIE") != -1;
        return isIE11orLess;
    }
    
        5
  •  6
  •   Eric Gerds    12 年前

    我想我有你要找的东西。您可以使用Javascript和clientCaps以字符串“a a.BB.CCCC.DDDD”获得完整版本的Internet Explorer。

    http://www.pinlady.net/PluginDetect/IE/

    它似乎适用于IE5.5及更高版本(包括IE10)。 它不受navigator.userAgent/document mode/browser模式的影响。 不需要条件注释或任何额外的HTML元素。这是一个纯Javascript解决方案。

    目前我还不确定IE Mobile的行为,但如果clientCaps方法失败,您可以始终使用备份检测方法。

    到目前为止,我得说,它工作得很好。

        6
  •  4
  •   jmbucknall    14 年前

    我想您已经回答了自己的问题:首先,它只检测IE,所以脚本实质上将把浏览器分为两部分:IE和<everythingelse>。

    其次,你必须在每一个HTML页面上添加一个看起来古怪的注释。考虑到像jQuery和YUI这样的范围广泛的JavaScript库必须“容易”地插入/利用大量的站点,您将自动使它们更难在门户之外使用。

        7
  •  3
  •   PleaseStand    14 年前

    navigator.userAgent 如果真的需要浏览器检测(而不是特征检测),jQuery使用它来获取信息。 $.browser 反对。这比在 每一个 第页。

        8
  •  2
  •   yckart Matthew Crumley    11 年前

    在这里您可以找到一些真正简单的浏览器检测方法: http://www.thespanner.co.uk/2009/01/29/detecting-browsers-javascript-hacks/

    var isIE = IE='\v'=='v';
    
        9
  •  2
  •   Viktor Fursov    11 年前

    我在用那个密码

    var isIE=navigator.userAgent.indexOf('MSIE')>-1;

        10
  •  2
  •   Jacksonkr    11 年前
    var version = navigator.userAgent.match(/(msie) (\d+)/i);
    console.log(version);
    

    我看了这个问题之后写得很快,以防有人想要。

    **编辑**

    约翰尼·达瓦尔的 在下面的评论中,我添加了一个链接,供任何试图发现的人使用 Internet Explorer 11 :

    http://blogs.msdn.com/b/ieinternals/archive/2013/09/21/internet-explorer-11-user-agent-string-ua-string-sniffing-compatibility-with-gecko-webkit.aspx

        11
  •  1
  •   ThiefMaster    14 年前

    检查浏览器是个坏主意-最好检查浏览器 特征 相反。例如,您通常会检查用户是否正在使用IE,因为您想使用IE中不支持的某些功能。但是,您知道所有当前和将来的非IE浏览器都将支持该功能吗?不。 因此,jQuery使用的方式更好:它创建并执行小的测试用例,检查某些bug/特性——您可以简单地检查if(browser_supports_XYZ)之类的东西,而不是检查用户是否使用特定的浏览器。

    无论如何,总会有一些情况需要检查浏览器,因为这是一个无法使用脚本进行测试的视觉错误。在这种情况下,最好使用javascript而不是条件注释,因为浏览器检查就在您需要的位置,而不是在其他位置(想象一个.js文件,您在其中检查从未在该文件中定义过的isIE)

        12
  •  0
  •   chiliNUT    10 年前

    对于我的用例,我只需要检测是否低于IE9,所以我使用

    if (document.body.style.backgroundSize === undefined && navigator.userAgent.indexOf('MSIE') > -1)
    {
    //IE8- stuff
    }
    
        13
  •  -1
  •   user123444555621    14 年前
    • 它污染了全局命名空间
    • 它需要在两个文件中进行更改。
    • 它只在IE中工作
    • 从技术上讲,有条件的评论仍然是评论
        14
  •  -1
  •   Ewen    13 年前

    这很管用,
    var isIe = !!window.ActiveXObject;

        15
  •  -1
  •   Douglas Held    10 年前

    为什么不直接用HTML5编程,然后检查一下

    if ( window.navigator.product !== "Gecko" )
    

    ?是的,这将把IE11包括在“壁虎”中,但是现在它还不够好吗?

    注意:HTML5规范说navigator.product必须返回“Gecko”。。。IE10和更早的版本都返回了一些其他的东西。

    推荐文章