如果我们网站的用户使用的是v9之前版本的Internet Explorer,我希望将他们弹出到一个错误页面。不值得我们花时间和金钱去支持iev9之前的版本。所有其他非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
}
}
这段代码能行吗?
为了阻止一些可能会出现在我面前的评论:
Yes, I know that users can forge their useragent string. I'm not concerned.
Yes, I know that programming pros prefer sniffing out feature-support instead of browser-type but I don't feel this approach makes sense in this case. I already know that all (relevant) non-IE browsers support the features that I need and that all pre-v9 IE browsers don't. Checking feature by feature throughout the site would be a waste.
Yes, I know that someone trying to access the site using IE v1 (or >= 20) wouldn't get 'badBrowser' set to true and the warning page wouldn't be displayed properly. That's a risk we're willing to take.
Yes, I know that Microsoft has "conditional comments" that can be used for precise browser version detection. IE no longer supports conditional comments as of IE 10, rendering this approach absolutely useless.
还有其他明显需要注意的问题吗?
这是我喜欢的做法。它提供了最大限度的控制。(注意:条件语句仅在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以及从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; } };
The usage is isIE.browser a property that returns a boolean and relies on conditional comments the method isIE.detectedVersion() which returns a number between 5 and 10. I am making the assumption that anything lower than 6 and you are in serious old school territory and you will something more beefy than a one liner and anything higher than 10 and you are in to newer territory. I have read something about IE11 not supporting conditional comments but I've not fully investigated, that is maybe for a later date.
无论如何,就像它一样,对于一行程序,它将涵盖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+,在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 repo: ie-version
更新:
更紧凑的版本可以写成一行:
return window.ActiveXObject === undefined ? null : !window.XMLHttpRequest ? 6 : !document.querySelector ? 7 : !document.addEventListener ? 8 : !window.atob ? 9 : !document.__proto__ ? 10 : 11;
如微软参考页所述,IE版本10不再支持条件注释。
var ieDetector = function() {
var browser = { // browser object
verIE: null,
docModeIE: null,
verIEtrue: null,
verIE_ua: null
},
tmp;
tmp = document.documentMode;
try {
document.documentMode = "";
} catch (e) {};
browser.isIE = typeof document.documentMode == "number" || eval("/*@cc_on!@*/!1");
try {
document.documentMode = tmp;
} catch (e) {};
// We only let IE run this code.
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 Help
"{3AF36230-A269-11D1-B5BF-0000F8051515}", // Offline Browsing Pack
"{89820200-ECBD-11CF-8B85-00AA005B4383}"
];
try {
obj.style.behavior = "url(#default#clientcaps)"
} catch (e) {};
for (x = 0; x < CLASSID.length; x++) {
try {
browser.verIEtrue = obj.getComponentVersion(CLASSID[x], "componentid").replace(/,/g, ".");
} catch (e) {};
if (browser.verIEtrue) break;
};
verTrueFloat = parseFloat(browser.verIEtrue || "0", 10);
browser.docModeIE = document.documentMode ||
((/back/i).test(document.compatMode || "") ? 5 : verTrueFloat) ||
browser.verIE_ua;
browser.verIE = verTrueFloat || browser.docModeIE;
};
return {
isIE: browser.isIE,
Version: browser.verIE
};
}();
document.write('isIE: ' + ieDetector.isIE + "<br />");
document.write('IE Version Number: ' + ieDetector.Version);
然后使用:
if((ieDetector.isIE) && (ieDetector.Version <= 9))
{
}
如果你需要删除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>
这种检测IE的方法结合了jKey使用条件注释的答案和Owen使用用户代理的答案的优点,并避免了它们的缺点。
jKey's approach works up to version 9 and immune to user agent spoofing in IE 8 & 9.
Owen's approach can fail on IE 5 & 6 (reporting 7) and is susceptible to UA spoofing, but it can detect IE versions >= 10 (now also including 12, which postdates Owen's answer).
// ----------------------------------------------------------
// A short snippet for detecting versions of IE
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
// ie === undefined
// Thus, to detect IE:
// if (ie) {}
// And to detect the version:
// ie === 6 // IE6
// ie > 7 // IE8, IE9 ...
// ----------------------------------------------------------
var ie = (function(){
var v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
if (v <= 4) { // Check for IE>9 using user agent
var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:|Edge\/)(\d+)/);
v = match ? 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 = [mixed];
}
for (var j = 0; j < mixed.length; j++) {
var re;
switch (mixed[j]) {
case 11:
re = /Trident.*rv\:11\./g;
break;
case 10:
re = /MSIE\s10\./g;
break;
case 9:
re = /MSIE\s9\./g;
break;
case 8:
re = /MSIE\s8\./g;
break;
case 7:
re = /MSIE\s7\./g;
break;
}
if (!!window.navigator.userAgent.match(re)) {
return true;
}
}
return false;
}
});
console.log(_.isIE());
console.log(_.isIE([7, 8, 9]));
console.log(_.isIE(11));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
下面的代码依赖标识了所有情况下的IE版本(IE<=9, IE10, IE11和IE/Edge)
function detectIE() {
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 (IE 12+) => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
// other browser
return false;
}
裁判:https://codepen.io/gapcode/pen/vEJNZN
不要把这么简单的事情过分复杂化。只需使用一个简单的JScript条件注释。它是最快的,因为它不需要向非IE浏览器添加代码来进行检测,而且它的兼容性可以追溯到支持HTML条件注释之前的IE版本。简而言之,
var IE_version=(-1/*@cc_on,@_jscript_version@*/);
小心小注释:大多数(如果不是全部)会将特殊条件注释误认为常规注释,并将其删除
基本上,上面的代码将IE_version的值设置为您正在使用的IE版本,或者-1(如果您没有使用IE)。现场演示:
var IE_version = (1 / * @cc_on @_jscript_version@ * /);
如果(IE_version ! = = 1) {
文档。write("<h1>You are using Internet Explorer " + IE_version + "</h1>");
}其他{
文档。write("<h1>您没有使用低于11的Internet Explorer版本</h1>");
}
这是基于条件注释只在旧版本的Internet Explorer中可见这一事实,而IE将@_jscript_version设置为浏览器的版本。例如,如果你使用Internet Explorer 7,那么@_jscript_version将被设置为7,因此,将执行的后处理javascript实际上是这样的:
var IE_version=(-1,7);
结果是7。
function getIEVersion(){
if (/MSIE |Trident\//.test( navigator.userAgent )=== false) return -1;
/**[IE <=9]*/
var isIE9L = typeof ( window.attachEvent ) === 'function' && !( Object.prototype.toString.call( window.opera ) == '[object Opera]' ) ? true : false;
var re;
if(isIE9L){
re = new RegExp( "MSIE ([0-9]{1,}[\.0-9]{0,})" );
if(re.exec( navigator.userAgent ) !== null)
return parseFloat( RegExp.$1 );
return -1;
}
/**[/IE <=9]*/
/** [IE >= 10]*/
if(navigator.userAgent.indexOf( 'Trident/' ) > -1){
re = new RegExp( "rv:([0-9]{1,}[\.0-9]{0,})" );
if(re.exec( navigator.userAgent ) !== null)
return parseFloat( RegExp.$1 );
return -1;
}
/**[/IE >= 10]*/
return -1;
};
点击这里==>
var ieVersion = getIEVersion();
if(ieVersion < 0){
//Not IE
}
//A version of IE
了解关于浏览器导航器的更多信息
https://developer.mozilla.org/en-US/docs/Web/API/Window/navigator