如果我们网站的用户使用的是 v9 之前的 Internet Explorer
版本,我想将他们退回到错误页面。只是不值得我们花时间和金钱来支持 IE pre-v9
。所有其他非 IE 浏览器的用户都很好,不应被退回。这是建议的代码:
if(navigator.appName.indexOf("Internet Explorer")!=-1){ //yeah, he's using IE
var badBrowser=(
navigator.appVersion.indexOf("MSIE 9")==-1 && //v9 is ok
navigator.appVersion.indexOf("MSIE 1")==-1 //v10, 11, 12, etc. is fine too
);
if(badBrowser){
// navigate to error page
}
}
这段代码能解决问题吗?
阻止一些可能会出现的评论:
是的,我知道用户可以伪造他们的用户代理字符串。我不担心。是的,我知道编程专业人员更喜欢嗅探功能支持而不是浏览器类型,但我认为这种方法在这种情况下没有意义。我已经知道所有(相关的)非 IE 浏览器都支持我需要的功能,而所有 v9 之前的 IE 浏览器都不支持。在整个站点中逐个检查功能将是一种浪费。是的,我知道有人尝试使用 IE v1(或 >= 20)访问该站点时不会将“badBrowser”设置为 true,并且警告页面也不会正确显示。这是我们愿意承担的风险。是的,我知道微软有“条件注释”,可用于精确的浏览器版本检测。从 IE 10 开始,IE 不再支持条件注释,这使得这种方法完全没用。
还有其他明显的问题需要注意吗?
这是我的首选方式。它提供了最大的控制。 (注意:条件语句仅在 IE5 - 9 中支持。)
首先正确设置你的ie类
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html> <!--<![endif]-->
<head>
然后你可以只使用 CSS 来制作样式异常,或者,如果你需要,你可以添加一些简单的 JavaScript:
(function ($) {
"use strict";
// Detecting IE
var oldIE;
if ($('html').is('.lt-ie7, .lt-ie8, .lt-ie9')) {
oldIE = true;
}
if (oldIE) {
// Here's your JS for IE..
} else {
// ..And here's the full-fat code for everyone else
}
}(jQuery));
感谢Paul Irish。
返回 IE 版本或者如果不是 IE 返回 false
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
例子:
if (isIE () == 8) {
// IE8 code
} else {
// Other versions IE or not IE
}
或者
if (isIE () && isIE () < 9) {
// is IE version less than 9
} else {
// is IE 9 and later or not IE
}
或者
if (isIE()) {
// is IE
} else {
// Other browser
}
"mozilla/5.0 (windows nt 6.3; wow64; trident/7.0; .net4.0e; .net4.0c; media center pc 6.0; .net clr 3.5.30729; .net clr 2.0.50727; .net clr 3.0.30729; rv:11.0) like gecko"
if (isIE () && isIE () < 9) {
使用条件注释。您正在尝试检测 IE < 9 的用户,并且条件注释将在这些浏览器中运行;在其他浏览器(IE >= 10 和非 IE)中,注释将被视为普通的 HTML 注释,它们就是这样。
示例 HTML:
<!--[if lt IE 9]>
WE DON'T LIKE YOUR BROWSER
<![endif]-->
如果需要,您也可以纯粹使用脚本执行此操作:
var div = document.createElement("div");
div.innerHTML = "<!--[if lt IE 9]><i></i><![endif]-->";
var isIeLessThan9 = (div.getElementsByTagName("i").length == 1);
if (isIeLessThan9) {
alert("WE DON'T LIKE YOUR BROWSER");
}
如果没有其他人添加了 addEventLister
方法并且您使用的是正确的浏览器模式,那么您可以检查 IE 8 或更低版本
if (window.attachEvent && !window.addEventListener) {
// "bad" IE
}
Legacy Internet Explorer and attachEvent (MDN)
轻松检测 MSIE (v6 - v7 - v8 - v9 - v10 - v11):
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
// MSIE
}
这是 AngularJS checks 用于 IE 的方式
/**
* documentMode is an IE-only property
* http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
*/
var msie = document.documentMode;
if (msie < 9) {
// code for IE < 9
}
为了可靠地过滤 IE8 和更早版本,可以使用 checking global objects:
if (document.all && !document.addEventListener) {
alert('IE8 or lower');
}
使用特性检测检测 IE 版本(IE6+,IE6 之前的浏览器被检测为 6,非 IE 浏览器返回 null):
var ie = (function (){
if (window.ActiveXObject === undefined) return null; //Not IE
if (!window.XMLHttpRequest) return 6;
if (!document.querySelector) return 7;
if (!document.addEventListener) return 8;
if (!window.atob) return 9;
if (!document.__proto__) return 10;
return 11;
})();
编辑:为方便起见,我创建了一个 bower/npm 存储库:ie-version
更新:
更紧凑的版本可以写成一行:
return window.ActiveXObject === undefined ? null : !window.XMLHttpRequest ? 6 : !document.querySelector ? 7 : !document.addEventListener ? 8 : !window.atob ? 9 : !document.__proto__ ? 10 : 11;
Detect IE in JS using conditional comments
// ----------------------------------------------------------
// 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;
}());
此函数将 IE 主要版本号作为整数返回,如果浏览器不是 Internet Explorer,则返回 undefined
。与所有用户代理解决方案一样,这很容易受到用户代理欺骗(自版本 8 以来一直是 IE 的官方功能)。
function getIEVersion() {
var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:)(\d+)/);
return match ? parseInt(match[1]) : undefined;
}
console.log(!!match && parseInt(match[1]))
、console.log(parseInt(match[1]))
和 console.log(match)
,但没有任何结果。
getIEVersion()
获取返回值。例如:if (getIEVersion() < 9) {/* IE 8 or below */}
if (!getIEVersion()) {/* Not IE */}
这对我有用。我将它用作重定向到一个页面,该页面解释了我们为什么不喜欢 < IE9 并提供指向我们喜欢的浏览器的链接。
<!--[if lt IE 9]>
<meta http-equiv="refresh" content="0;URL=http://google.com">
<![endif]-->
您的代码可以进行检查,但正如您所想,如果有人尝试使用 IE v1 或 > v19 访问您的页面,则不会出现错误,因此使用 Regex 表达式进行检查可能更安全,如下面的代码:
var userAgent = navigator.userAgent.toLowerCase();
// Test if the browser is IE and check the version number is lower than 9
if (/msie/.test(userAgent) &&
parseFloat((userAgent.match(/.*(?:rv|ie)[\/: ](.+?)([ \);]|$)/) || [])[1]) < 9) {
// Navigate to error page
}
从版本 10 开始,IE 不再支持条件注释,如 Microsoft reference page 中所述。
var ieDetector = function() { var browser = { // 浏览器对象 verIE: null, docModeIE: null, verIEtrue: null, verIE_ua: null }, tmp; tmp = document.documentMode;尝试 { document.documentMode = ""; } 捕捉 (e) {}; browser.isIE = typeof document.documentMode == "数字" || eval("/*@cc_on!@*/!1");尝试 { document.documentMode = tmp; } 捕捉 (e) {}; // 我们只让 IE 运行这段代码。 if (browser.isIE) { browser.verIE_ua = (/^(?:.*?[^a-zA-Z])??(?:MSIE|rv\s*\:)\s*(\d+\ .?\d*)/i).test(navigator.userAgent || "") ? parseFloat(RegExp.$1, 10) : null; var e, verTrueFloat, x, obj = document.createElement("div"), CLASSID = [ "{45EA75A0-A269-11D1-B5BF-0000F8051515}", // Internet Explorer 帮助 "{3AF36230-A269-11D1-B5BF- 0000F8051515}", // 离线浏览包 "{89820200-ECBD-11CF-8B85-00AA005B4383}" ];尝试 { obj.style.behavior = "url(#default#clientcaps)" } 捕捉 (e) {}; for (x = 0; x < CLASSID.length; x++) { try { browser.verIEtrue = obj.getComponentVersion(CLASSID[x], "componentid").replace(/,/g, "."); } 捕捉 (e) {};如果(browser.verIEtrue)中断; }; verTrueFloat = parseFloat(browser.verIEtrue || "0", 10); browser.docModeIE = 文档.documentMode || ((/back/i).test(document.compatMode || "") ? 5 : verTrueFloat) || browser.verIE_ua; browser.verIE = verTrueFloat || browser.docModeIE; };返回 { isIE: browser.isIE, 版本: browser.verIE }; }(); document.write('isIE: ' + ieDetector.isIE + "
"); document.write('IE 版本号:' + ieDetector.Version);
然后使用:
if((ieDetector.isIE) && (ieDetector.Version <= 9))
{
}
version 11
编辑:这段代码太棒了!哈哈,它给了一个里面所有东西的对象。版本是 11,但 docModeIR 等于 9。谢谢!
对于即 10 和 11:
您可以使用js并在html中添加一个类来保持conditional comments的标准:
var ua = navigator.userAgent,
doc = document.documentElement;
if ((ua.match(/MSIE 10.0/i))) {
doc.className = doc.className + " ie10";
} else if((ua.match(/rv:11.0/i))){
doc.className = doc.className + " ie11";
}
或者使用像 bowser 这样的库:
或用于特征检测的modernizr:
这已经被回答到死了,但这就是你所需要的。
!!navigator.userAgent.match(/msie\s[5-8]/i)
var Browser = new function () {
var self = this;
var nav = navigator.userAgent.toLowerCase();
if (nav.indexOf('msie') != -1) {
self.ie = {
version: toFloat(nav.split('msie')[1])
};
};
};
if(Browser.ie && Browser.ie.version > 9)
{
// do something
}
要检测 Internet Explorer 10|11,您可以在 body 标记之后立即使用这个小脚本:
在我的情况下,我使用加载在 head 中的 jQuery 库。
<!DOCTYPE HTML>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<script>if (navigator.appVersion.indexOf('Trident/') != -1) $("body").addClass("ie10");</script>
</body>
</html>
根据Microsoft,以下是最好的解决方案,也很简单:
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
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 );
}
我发现用于检查 IE 版本的最全面的 JS 脚本是 http://www.pinlady.net/PluginDetect/IE/。整个库位于 http://www.pinlady.net/PluginDetect/Browsers/。
IE10 不再支持条件语句。
在 IE11 中,用户代理不再包含 MSIE。此外,使用用户代理是不可靠的,因为它可以被修改。
使用 PluginDetect JS 脚本,您可以使用针对特定 IE 版本的非常具体且精心设计的代码来检测 IE 并检测确切的版本。当您确切关心您正在使用的浏览器版本时,这非常有用。
我将建议不要无数次重写此代码。我建议您使用 Conditionizr 库 (http://conditionizr.com/),它能够测试特定 IE 版本以及其他浏览器、操作系统,甚至是否存在 Retina 显示器。
仅包含您需要的特定测试的代码,并且您还可以获得经过多次迭代的测试库的好处(并且可以在不破坏代码的情况下轻松升级)。
它还与 Modernizr 很好地结合在一起,它可以处理所有那些你最好测试特定功能而不是特定浏览器的情况。
我喜欢这样:
<script>
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
var ua = window.navigator.userAgent;
//Internet Explorer | if | 9-11
if (isIE () == 9) {
alert("Shut down this junk! | IE 9");
} else if (isIE () == 10){
alert("Shut down this junk! | IE 10");
} else if (ua.indexOf("Trident/7.0") > 0) {
alert("Shut down this junk! | IE 11");
}else{
alert("Thank god it's not IE!");
}
</script>
这种检测 IE 的方法结合了 jKey 使用条件注释的答案和 Owen 使用用户代理的答案的优点并避免了缺点。
jKey 的方法适用于版本 9,并且不受 IE 8 和 9 中用户代理欺骗的影响。
Owen 的方法在 IE 5 和 6(报告 7)上可能会失败,并且容易受到 UA 欺骗,但它可以检测到 IE 版本 >= 10(现在还包括 12,这是 Owen 的回答之后的版本)。 //------------------------------------------------ ---------- // 用于检测 IE 版本的简短片段 // ---------------------------- ------------------------------ // 如果你不在 IE 中(或者 IE 版本低于 5)那么: // ie === undefined // 因此,检测 IE: // if (ie) {} // 并检测版本: // ie === 6 // IE6 // ie > 7 // IE8, IE9 ... // -------------------------------------------- -------------- var ie = (function(){ var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); 而( div.innerHTML = '', all[0] ); if ( v <= 4) { // 使用用户代理检查 IE>9 var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:|Edge\/)(\d+)/) ; v = 匹配 ? parseInt(match[1]) : undefined; } return v; }());
这可用于为包含 IE 版本的文档设置有用的类:
if (ie) {
document.documentElement.className += ' ie' + ie;
if (ie < 9)
document.documentElement.className += ' ieLT9';
}
请注意,如果 IE 处于兼容模式,它会检测正在使用的兼容模式。另请注意,IE 版本对旧版本(<10)最有用;更高的版本更符合标准,最好使用诸如modernizr.js之类的东西来检查功能。
我为此做了一个方便的下划线混合。
_.isIE(); // Any version of IE?
_.isIE(9); // IE 9?
_.isIE([7,8,9]); // IE 7, 8 or 9?
_.mixin({ isIE: function(mixed) { if (_.isUndefined(mixed)) { mixed = [7, 8, 9, 10, 11]; } else if (_.isNumber(mixed)) { mixed = [混合]; } for (var j = 0; j < mixed.length; j++) { var re; switch (mixed[j]) { case 11: re = /Trident.*rv\:11\./g;中断;案例 10:re = /MSIE\s10\./g;中断;案例 9:re = /MSIE\s9\./g;中断;案例 8:re = /MSIE\s8\./g;中断;案例 7: re = /MSIE\s7\./g; break; } if (!!window.navigator.userAgent.match(re)) { return true; } } return false; } });控制台.log(_.isIE()); console.log(_.isIE([7, 8, 9]));控制台.log(_.isIE(11));
或者干脆
// IE 10: ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
// IE 11: ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
// Edge 12: ua = '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: ua = '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';
var isIE = navigator.userAgent.match(/MSIE|Trident|Edge/)
var IEVersion = ((navigator.userAgent.match(/(?:MSIE |Trident.*rv:|Edge\/)(\d+(\.\d+)?)/)) || []) [1]
我意识到我在这里聚会有点晚了,但我一直在检查一种简单的单行方式来提供有关浏览器是否是 IE 以及它是 10 以后的版本的反馈。我没有为版本 11 编写此代码,因此可能需要对此进行一些修改。
然而,这是代码,它作为一个具有属性和方法的对象工作,并且依赖于对象检测而不是抓取导航器对象(它存在大量缺陷,因为它可以被欺骗)。
var isIE = { browser:/*@cc_on!@*/false, detectedVersion: function () { return (typeof window.atob !== "undefined") ? 10 : (typeof document.addEventListener !== "undefined") ? 9 : (typeof document.querySelector !== "undefined") ? 8 : (typeof window.XMLHttpRequest !== "undefined") ? 7 : (typeof document.compatMode !== "undefined") ? 6 : 5; } };
用法是 isIE.browser
一个返回布尔值的属性并依赖于条件注释方法 isIE.detectedVersion()
返回一个介于 5 和 10 之间的数字。我假设任何低于 6 的值,并且您处于严肃的老派领域,并且你会比一个班轮和任何高于 10 的东西更强壮,你会进入更新的领域。我读过一些关于 IE11 不支持条件评论的内容,但我还没有完全调查,可能是以后的日期。
无论如何,就目前而言,它会涵盖 IE 浏览器和版本检测的基础知识。它远非完美,但它很小且易于修改。
仅供参考,如果有人对如何实际实现这一点有任何疑问,那么以下条件应该会有所帮助。
var isIE = { browser:/*@cc_on!@*/false, detectedVersion: function () { return (typeof window.atob !== "undefined") ? 10 : (typeof document.addEventListener !== "undefined") ? 9 : (typeof document.querySelector !== "undefined") ? 8 : (typeof window.XMLHttpRequest !== "undefined") ? 7 : (typeof document.compatMode !== "undefined") ? 6 : 5; } };
/* testing IE */
if (isIE.browser) {
alert("This is an IE browser, with a detected version of : " + isIE.detectedVersion());
}
检测 IE 及其版本再简单不过了,您只需要一点原生/原版 Javascript:
var uA = navigator.userAgent;
var browser = null;
var ieVersion = null;
if (uA.indexOf('MSIE 6') >= 0) {
browser = 'IE';
ieVersion = 6;
}
if (uA.indexOf('MSIE 7') >= 0) {
browser = 'IE';
ieVersion = 7;
}
if (document.documentMode) { // as of IE8
browser = 'IE';
ieVersion = document.documentMode;
}
这是一种使用它的方法:
if (browser == 'IE' && ieVersion <= 9)
document.documentElement.className += ' ie9-';
.
适用于所有 IE 版本,包括较低兼容性视图/模式下的更高版本,并且 documentMode
是 IE 专有的。
如果您需要选择 IE 浏览器版本,则可以按照以下代码进行操作。此代码适用于 IE6 到 IE11 版本
<!DOCTYPE html>
<html>
<body>
<p>Click on Try button to check IE Browser version.</p>
<button onclick="getInternetExplorerVersion()">Try it</button>
<p id="demo"></p>
<script>
function getInternetExplorerVersion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
var rv = -1;
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
{
if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
//For IE 11 >
if (navigator.appName == 'Netscape') {
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1);
alert(rv);
}
}
else {
alert('otherbrowser');
}
}
else {
//For < IE11
alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
}
return false;
}}
</script>
</body>
</html>
Window 运行 IE10 会自动更新到 IE11+ 并且会标准化 W3C
现在,我们不需要支持 IE8-
<!DOCTYPE html>
<!--[if lt IE 9]><html class="ie ie8"><![endif]-->
<!--[if IE 9]><html class="ie ie9"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html><!--<![endif]-->
<head>
...
<!--[if lt IE 8]><meta http-equiv="Refresh" content="0;url=/error-browser.html"><![endif]--
...
</head>
var isIE9OrBelow = function()
{
return /MSIE\s/.test(navigator.userAgent) && parseFloat(navigator.appVersion.split("MSIE")[1]) < 10;
}
if (!document.addEventListener) {
// ie8
} else if (!window.btoa) {
// ie9
}
// others
Error: Saw <!-- within a comment. Probable cause: Nested comment (not allowed). At line 5, column 21 if gt IE 8]><!--><html