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

发布于 2024-10-02 08:25:00 字数 949 浏览 8 评论 0原文

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

  • jQuery 似乎在页面的 DOM 中添加了一个临时对象来检测某些功能,
  • YUI2 在其 YAHOO.env.ua = function() 中的用户代理上执行正则表达式(文件 yahoo.js< /code>)

阅读此答案后我认为这是真的,为了检测 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>

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

if(window.isIE)
   ...

除了这可能会导致痛苦,因为它必须添加到所有页面中,是否有任何我可能不知道的问题/注意事项?


仅供参考:我知道最好使用 对象检测而不是浏览器检测,但在某些情况下您仍然必须使用浏览器检测。

In order to detect IE most Javascript libaries do all sort of tricks.

  • jQuery seem to add a temporary object into your pages's DOM to detect some features,
  • YUI2 does regex on the user agent in its YAHOO.env.ua = function() (file yahoo.js)

After reading this answer it came in my mind that it's true, in order to detect simply IE in Javascript we could simply add to our pages:

<!--[if IE]><script type="text/javascript">window['isIE'] = true;</script><![endif]-->

<script type="text/javascript" src="all-your-other-scripts-here.js"></script>

Now the window.isIE variable is set for all our Javascript code, by simply doing:

if(window.isIE)
   ...

Beside the fact that this might result in being a pain because it has to be added in all pages, are there any issues/considerations I might be unaware of?


FYI: I know it's better to use object detection rather than browser detection, but there are cases where you still have to use browser detection.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

用心笑 2024-10-09 08:25:00

James Padolsey 在 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;

}());

当然,所有学分都应归于 James ,我只是信使(但如果我的复制粘贴操作出错,请射击信使)。

还要查看创建的分叉。 Paul Irish 在评论中解释了内部工作原理。

James Padolsey put a little snippet on GitHub that I'll quote here:

// ----------------------------------------------------------
// 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;

}());

Of course all credits should go to James, I'm only the messenger (but please shoot the messenger if my copy-paste action erred).

Also look at the forks that were created. Paul Irish explained the inner workings in a comment.

傲性难收 2024-10-09 08:25:00

如果你想这样做,我认为最好使用条件编译,因为你可以在 javascript 中完成它,而不需要更改 html:

var isIE = /*@cc_on!@*/false;

If you want to do it that way, I think it's much better to use Conditional Compilation instead as you can do it inside the javascript without requiring to change the html:

var isIE = /*@cc_on!@*/false;
我一向站在原地 2024-10-09 08:25:00

Marcel Korpel 的答案不再有效(在 IE 10 中它返回 undef,因此 IE 10 显示为不是 IE)。注意:现已更新,也可与 IE 11 配合使用。

这是该代码的变体,但来自 微软的建议。如果您使用的是以前的代码,则可以直接替换此代码,因为它的构建方式是完全相同的。

与条件注释/编译不同,它也应该与最小化器一起正常工作。

// ----------------------------------------------------------
// 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”提供了我修复的代码!

Marcel Korpel's answer no longer works (in IE 10 it returns undef, so IE 10 appears as not being IE). NOTE: Now updated to work with IE 11 also.

This is a variant of that code, but which comes from Microsoft's recommendations. If you were using the previous code, you can just drop in this replacement since it is built to be called the exact same way.

Unlike conditional comments/compilation, it should also work fine with minimizers.

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

updated to work with IE11. Thanks 'acarlon' for pointing out that it wasn't working, and 'mario' for code that I based the fix on!

往日 2024-10-09 08:25:00

IE 11 发生了很大变化,现在许多过去的浏览器检测方法都不起作用了。以下代码适用于 IE 11 及更早版本。

function isIE()
{
    var isIE11 = navigator.userAgent.indexOf(".NET CLR") > -1;      
    var isIE11orLess = isIE11 || navigator.appVersion.indexOf("MSIE") != -1;
    return isIE11orLess;
}

IE 11 has changed a lot and now many past methods of browser detection do not work. The below code works for IE 11 and earlier.

function isIE()
{
    var isIE11 = navigator.userAgent.indexOf(".NET CLR") > -1;      
    var isIE11orLess = isIE11 || navigator.appVersion.indexOf("MSIE") != -1;
    return isIE11orLess;
}
不必了 2024-10-09 08:25:00

我想我有你正在寻找的东西。您可以使用 Javascript 和 clientCaps 以字符串“AA.BB.CCCC.DDDD”形式获取完整版本的 Internet Explorer。

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

它似乎适用于 IE 5.5 及更高版本(包括即10)。
它不受 navigator.userAgent/文档模式/浏览器模式的影响。
不需要条件注释或任何额外的 HTML 元素。这是一个纯 Javascript 解决方案。

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

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

I think I have what you are looking for. You can get the Full Version of Internet Explorer as a string "AA.BB.CCCC.DDDD" using Javascript and clientCaps.

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

It appears to work for IE 5.5 and higher (including IE 10).
It is immune to the navigator.userAgent/document mode/browser mode.
There is no need for conditional comments, or any extra HTML elements. It is a pure Javascript solution.

I am not certain at this time how IE Mobile behaves, but you can always use a backup detection method in case this clientCaps method fails.

So far, I gotta say, it works pretty well.

吃颗糖壮壮胆 2024-10-09 08:25:00

我认为您回答了自己的问题:首先,它只检测 IE,因此该脚本本质上会将浏览器的世界分为两部分:IE 和

其次,您必须向每个 HTML 页面添加看起来很奇怪的注释。鉴于 jQuery 和 YUI 等广泛的 JavaScript 库必须能够“轻松”地插入/用于广泛的站点,因此您会自然而然地使它们更难以使用。

I think you answered your own question: first, it only detects IE, so the script would in essence be splitting the universe of browsers into 2 parts: IE and <everythingelse>.

Second, you'd have to add a wacky looking comment to every HTML page. Given that wide-ranging JavaScript libraries like jQuery and YUI have to be "easy" to insert/utilize for a breadth of sites, you would automatically be making them harder to use out of the gate.

沫尐诺 2024-10-09 08:25:00

如果确实需要浏览器检测(而不是功能检测),则存在 navigator.userAgent ,并且 jQuery 使用它来获取 $.browser 对象的信息。这比必须在每个页面中包含特定于 IE 的条件注释要好得多。

navigator.userAgent exists if browser detection (rather than feature detection) is really needed, and jQuery uses it to get the information for the $.browser object. It's much nicer than having to include an IE-specific conditional comment in every page.

℉絮湮 2024-10-09 08:25:00

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

var isIE = IE='\v'=='v';

Here you can find some really simple hacks for browser-detecting: http://www.thespanner.co.uk/2009/01/29/detecting-browsers-javascript-hacks/

var isIE = IE='\v'=='v';
无所谓啦 2024-10-09 08:25:00

我正在使用该代码

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

I'm using that code

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

破晓 2024-10-09 08:25:00
var version = navigator.userAgent.match(/(msie) (\d+)/i);
console.log(version);

看了这个问题后我很快就写了一些东西,以防有人想要它。

** 编辑 **

根据下面 Johnny Darvall 的评论,我为任何试图嗅探 Internet Explorer 11 的人添加了一个链接:

http://blogs.msdn.com/b/ieinternals/archive/2013/09/21/internet-explorer-11-user-agent-string-ua-string-sniffing -与-gecko-webkit.aspx的兼容性

var version = navigator.userAgent.match(/(msie) (\d+)/i);
console.log(version);

something quick I wrote quick after looking at this question in case anyone wants it.

** EDIT **

Per Johnny Darvall's comment below, I'm adding a link for anyone who is trying to sniff out 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

总以为 2024-10-09 08:25:00

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

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

Checking for browsers is a bad idea - it's better to check for browser features instead. For example, usually you check if the user is using IE because you want to use some feature not supported in IE. However, can you know ALL current and future non-IE browsers will support that feature? No.
So the way e.g. used by jQuery is better: It creates and executes small testcases checking for certain bugs/features - and you can simply check stuff like if(browser_supports_XYZ) instead of checking if the user is using a specific browser.

Anyway, there are always cases where checking for the browser is necessary because it's a visual bug you cannot test for using a script. In this case it's better to use javascript instead of conditional comments because you have the browser check right at the position where you need it instead of at some other place (imagine a .js file where you check for isIE which is never defined in that file)

蓝天白云 2024-10-09 08:25:00

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

if (document.body.style.backgroundSize === undefined && navigator.userAgent.indexOf('MSIE') > -1)
{
//IE8- stuff
}

For my use case, I really just need to detect if lower than IE9, so I use

if (document.body.style.backgroundSize === undefined && navigator.userAgent.indexOf('MSIE') > -1)
{
//IE8- stuff
}
心在旅行 2024-10-09 08:25:00
  • 它污染了全局命名空间
  • 它需要更改两个文件。
  • 它仅适用于 IE
  • 从技术上讲,条件注释仍然是注释
  • It pollutes global namespace
  • It requires changes in two files.
  • It works in IE only
  • Technically, a conditional comment is still a comment
冷情 2024-10-09 08:25:00

这效果很好,
var isIe = !!window.ActiveXObject;

This works quite well,
var isIe = !!window.ActiveXObject;

堇年纸鸢 2024-10-09 08:25:00

为什么不直接用 HTML5 编程并检查一下

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

?确实,这将把 IE11 纳入“Gecko”系列中,但现在它不是应该已经足够好了了吗?

注意:HTML5 规范。说 navigator.product 必须返回“Gecko”...而 IE10 及更早版本都返回其他内容。

Why don't you just program in HTML5, and check that

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

?? True, this will include IE11 in the "Gecko" bunch, but isn't it supposed to be good enough now?

Note: the HTML5 spec. says that navigator.product must return "Gecko"... and IE10 and earlier all return something else.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文