为什么使用window.navigator.userAgent检索浏览器Explorer 11被识别为Mozilla?如何检索用户代理和版本?

Why using window.navigator.userAgent to retrieve the browser Explorer 11 is recognized as Mozilla? How retrieve the user angent and version?

我是 JavaScript 和 JQuery 的新手,我正在疯狂地尝试实现一个简单的脚本来检测浏览器是否为 Internet Explorer及其版本。

所以我正在做这样的事情:

$( document ).ready(function() {

    //alert(navigator.appName);
    //alert(navigator.appCodeName);
    //alert(navigator.appVersion);
    //alert(navigator.platform);
    //alert(window.navigator.userAgent);

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    console.log("USER AGENT: " + ua);
    console.log("MSIE: " + msie);
});

问题是 运行 页面进入 Explorer 11 进入控制台日志 我得到这条消息:

USER AGENT: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; InfoPath.3; GWX:QUALIFIED; ASU2JS; rv:11.0) like Gecko

MSIE: -1

怎么可能被识别为 Mozilla 而不是 IE?

我需要识别浏览器是否为 Internet Explorer 及其版本。

如何进行这个操作?

根据 Microsoft 的说法,IE11 的用户代理字符串专门用于诱骗 UA 解析器将其识别为其他内容。 资料来源:http://blogs.msdn.com/b/ieinternals/archive/2013/09/21/internet-explorer-11-user-agent-string-ua-string-sniffing-compatibility-with-gecko-webkit.aspx

即使在上面的文章中提到了这一点,我也会重复。 如果你想做UA嗅探,请三思。特征检测是处理浏览器兼容性的推荐方法。有关详细信息,请参阅文章。

请尝试下面的代码。

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.);
                    alert(rv);
                }
            }
            else {
                alert('otherbrowser');
            }
        }
        else {
            //For < IE11
            alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
        }
        return false;
    }}

IE 11 的发布破坏了所有客户端检查脚本。如您所说,它现在报告为 "Mozilla",不再报告 MSIE。据我所知,他们做出的决定是这样做的,因为 IE11 应该更多地基于 Gecko 引擎而不是 Mozilla。为了说明这一点,Microsoft 决定将 User-Agent 字符串更改为不同的内容。我知道测试 IE11 的最佳方法是检查 "Trident/7.0",所有 IE11 浏览器都应该通知它。

Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko

无论如何,正如许多人所建议的那样,最好检查功能而不是依赖浏览器检查。