Javascript IE 检测,为什么不使用简单的条件注释?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4169160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript IE detection, why not use simple conditional comments?
提问by Marco Demaio
In order to detect IE most Javascript libaries do all sort of tricks.
为了检测 IE,大多数 Javascript 库会使用各种技巧。
- 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()
(fileyahoo.js
)
- jQuery 似乎在页面的 DOM 中添加了一个临时对象来检测某些功能,
- YUI2 在其
YAHOO.env.ua = function()
(文件yahoo.js
)中的用户代理上执行正则表达式
After reading this answerit came in my mind that it's true, in order to detect simply IE in Javascript we could simply add to our pages:
在阅读了这个答案后,我想到这是真的,为了在 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>
Now the window.isIE
variable is set for all our Javascript code, by simply doing:
现在window.isIE
为我们所有的 Javascript 代码设置变量,只需执行以下操作:
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.
仅供参考:我知道最好使用对象检测而不是浏览器检测,但在某些情况下您仍然必须使用浏览器检测。
回答by Marcel Korpel
James Padolsey put a little snippet on GitHubthat I'll quote here:
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;
}());
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.
还要查看创建的分叉。Paul Irish 在评论中解释了内部运作。
回答by AlfonsoML
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:
如果你想这样做,我认为最好使用条件编译,因为你可以在 javascript 中完成它,而无需更改 html:
var isIE = /*@cc_on!@*/false;
回答by Sean Colombo
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.
Marcel Korpel 的回答不再有效(在 IE 10 中它返回 undef,因此 IE 10 看起来不是 IE)。注意:现在更新后也可以与 IE 11 一起使用。
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.
这是该代码的变体,但来自Microsoft 的建议。如果您使用的是以前的代码,则可以直接删除此替换代码,因为它的构建方式是完全相同的。
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!
更新以使用 IE11。感谢 'acarlon' 指出它不起作用,感谢 'mario' 指出我基于修复的代码!
回答by webber55
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.
IE 11 发生了很大变化,现在许多过去的浏览器检测方法都不起作用。以下代码适用于 IE 11 及更早版本。
function isIE()
{
var isIE11 = navigator.userAgent.indexOf(".NET CLR") > -1;
var isIE11orLess = isIE11 || navigator.appVersion.indexOf("MSIE") != -1;
return isIE11orLess;
}
回答by Eric Gerds
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.
我想我有你要找的东西。您可以使用 Javascript 和 clientCaps 以字符串“AA.BB.CCCC.DDDD”的形式获取 Internet Explorer 的完整版本。
http://www.pinlady.net/PluginDetect/IE/
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.
它似乎适用于 IE 5.5 及更高版本(包括 IE 10)。它不受 navigator.userAgent/document mode/browser mode 的影响。不需要条件注释或任何额外的 HTML 元素。它是一个纯 Javascript 解决方案。
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.
我目前不确定 IE Mobile 的行为方式,但您始终可以使用备份检测方法,以防此 clientCaps 方法失败。
So far, I gotta say, it works pretty well.
到目前为止,我得说,它工作得很好。
回答by jmbucknall
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>.
我想你回答了你自己的问题:首先,它只检测 IE,所以脚本本质上将把浏览器的世界分成两部分:IE 和 <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.
其次,您必须向每个 HTML 页面添加看起来古怪的注释。考虑到像 jQuery 和 YUI 这样范围广泛的 JavaScript 库必须“易于”插入/用于广泛的站点,因此您会自动使它们更难使用。
回答by PleaseStand
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 everypage.
navigator.userAgent
如果确实需要浏览器检测(而不是特征检测),则存在,jQuery 使用它来获取$.browser
对象的信息。这比必须在每个页面中包含特定于 IE 的条件注释要好得多。
回答by yckart
Here you can find some really simple hacks for browser-detecting: http://www.thespanner.co.uk/2009/01/29/detecting-browsers-javascript-hacks/
在这里你可以找到一些非常简单的浏览器检测技巧:http: //www.thespanner.co.uk/2009/01/29/detecting-browsers-javascript-hacks/
var isIE = IE='\v'=='v';
回答by Hymansonkr
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'scomment below, I'm adding a link for anyone who is trying to sniff out Internet Explorer 11:
根据下面约翰尼·达瓦尔 (Johnny Darvall) 的评论,我为任何试图嗅出Internet Explorer 11 的人添加了一个链接:
回答by Viktor Fursov
I'm using that code
我正在使用该代码
var isIE = navigator.userAgent.indexOf(' MSIE ') > -1;
var isIE = navigator.userAgent.indexOf(' MSIE ') > -1;