如果我们网站的用户使用的是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.

还有其他明显需要注意的问题吗?


当前回答

或者简单地

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

其他回答

我为此做了一个方便的下划线混合。

_.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版本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))
{

}

我建议不要再重写这段代码了。我建议你使用Conditionizr库(http://conditionizr.com/),它能够测试特定的IE版本以及其他浏览器、操作系统,甚至是否有视网膜显示。

只包含您需要的特定测试的代码,您还可以获得经过多次迭代的测试库的好处(并且很容易升级而不会破坏您的代码)。

它还可以很好地与Modernizr配合,Modernizr可以处理所有情况,在这些情况下,您最好测试特定的功能,而不是特定的浏览器。

返回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
}

or

if (isIE () && isIE () < 9) {
 // is IE version less than 9
} else {
 // is IE 9 and later or not IE
}

or

if (isIE()) {
 // is IE
} else {
 // Other browser
}

我意识到我在这里有点晚了,但我一直在检查一个简单的一行方式来提供关于浏览器是否是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());
}