如何使用JavaScript确定确切的浏览器和版本?


当前回答

我发现了一个有趣又快捷的方法。 IE支持导航器。systemLanguage返回“en-US”,其他浏览器返回undefined。

<script>
    var lang = navigator.systemLanguage;
    if (lang!='en-US'){document.write("Well, this is not internet explorer");}
    else{document.write("This is internet explorer");}
</script>

其他回答

navigator.saysWho = (() => { const { userAgent } = navigator let match = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [] let temp if (/trident/i.test(match[1])) { temp = /\brv[ :]+(\d+)/g.exec(userAgent) || [] return `IE ${temp[1] || ''}` } if (match[1] === 'Chrome') { temp = userAgent.match(/\b(OPR|Edge)\/(\d+)/) if (temp !== null) { return temp.slice(1).join(' ').replace('OPR', 'Opera') } temp = userAgent.match(/\b(Edg)\/(\d+)/) if (temp !== null) { return temp.slice(1).join(' ').replace('Edg', 'Edge (Chromium)') } } match = match[2] ? [ match[1], match[2] ] : [ navigator.appName, navigator.appVersion, '-?' ] temp = userAgent.match(/version\/(\d+)/i) if (temp !== null) { match.splice(1, 1, temp[1]) } return match.join(' ') })() console.log(navigator.saysWho) // outputs: `Chrome 89`

顾名思义,这将告诉您浏览器提供的名称和版本号。

当您在多个浏览器上测试新代码时,对测试和错误结果进行排序非常方便。

如果你想要一个返回浏览器和版本的函数,这里是对原始答案的改进:

navigator.browserInfo = 
(
    function()
    {
        var browser = '';
        var version = '';
        var idString = '';

        var ua = navigator.userAgent;
        var tem = [];
        var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i);

        //IE will be identified as 'Trident' and a different version number. The name must be corrected to 'Internet Explorer' and the correct version identified.
        //ie correction
        if(/trident/i.test(M[1]))
        {
            tem = /\brv[ :]+(\d+.?\d*)/g.exec(ua) || [];
            browser = 'Internet Explorer';
            version = tem[1];
        }

        //firefox
        else if(/firefox/i.test(M[1]))
        {
            tem = /\brv[ :]+(\d+.?\d*)/g.exec(ua) || [];
            browser = 'Firefox';
            version = tem[1];
        }

        //safari
        else if(/safari/i.test(M[1]))
        {
            tem = ua.match(/\bVersion\/(\d+.?\d*\s*\w+)/);
            browser = 'Safari';
            version = tem[1];
        }

        //If 'Chrome' is found, it may be another browser. 
        else if(M[1] === 'Chrome')
        {
            //opera
            var temOpr = ua.match(/\b(OPR)\/(\d+.?\d*.?\d*.?\d*)/);
            //edge
            var temEdge = ua.match(/\b(Edge)\/(\d+.?\d*)/);
            //chrome
            var temChrome = ua.match(/\b(Chrome)\/(\d+.?\d*.?\d*.?\d*)/);

            //a genuine 'Chrome' reading will result from ONLY temChrome not being null.
            var genuineChrome = temOpr == null && temEdge == null && temChrome != null;

            if(temOpr != null)
            {
                browser = temOpr[1].replace('OPR', 'Opera');
                version = temOpr[2];
            }

            if(temEdge != null)
            {
                browser = temEdge[1];
                version = temEdge[2];
            }

            if(genuineChrome)
            {
                browser = temChrome[1];
                version = temChrome[2];
            }
        }
        //There will be some odd balls, so if you wish to support those browsers, add functionality to display those browsers as well.

        if(browser == '' || version == '')
        {
            idString = 'We couldn\'t find your browser, but you can still use the site';
        }
        else
        {
            idString = browser + ' version ' + version;
        }

        alert('Your browser is ' + idString);

        //store the type of browser locally
        if(typeof(Storage) !== "undefined")
        {
            //Store
            localStorage.setItem('browser', browser);
            localStorage.setItem('version', version);
        } 
        else
        {
            alert('local storage not available');
        }
    }
)();

这样,它还将结果存储在本地,因此不必每次都执行该检查。

我推荐使用小型javascript库Bowser。它基于导航器。userAgent和相当好测试的所有浏览器,包括iphone, android等。

https://github.com/ded/bowser

你可以简单地说:

if (bowser.msie && bowser.version <= 6) {
  alert('Hello IE');
} else if (bowser.firefox){
  alert('Hello Foxy');
} else if (bowser.chrome){
  alert('Hello Chrome');
} else if (bowser.safari){
  alert('Hello Safari');
} else if(bowser.iphone || bowser.android){
  alert('Hello mobile');
}

通常最好尽可能避免使用特定于浏览器的代码。JQuery $。属性可用于检测对特定特性的支持,而不是依赖于浏览器名称和版本。

以Opera为例,你可以伪造internet explorer或firefox实例。

JQuery的详细描述。支持可以在这里找到:http://api.jquery.com/jQuery.support/

现在根据jQuery弃用。

我们强烈建议使用外部库,如Modernizr 而不是依赖于jQuery.support中的属性。

在编写网站代码时,我总是确保,像导航这样的基本功能对非js用户也是可以访问的。这可能是讨论的对象,如果主页是针对特殊受众,可以忽略。

你可以扫描用户代理来查找浏览器名称,而不是硬编码web浏览器:

navigator.userAgent.split(')').reverse()[0].match(/(?!Gecko|Version|[A-Za-z]+?Web[Kk]it)[A-Z][a-z]+/g)[0]

我已经在Safari、Chrome和Firefox上进行了测试。如果您发现这在浏览器上不起作用,请告诉我。

Safari:“旅行” 铬:“铬” Firefox:“火狐”

如果需要,您甚至可以修改它以获得浏览器版本。请注意,有更好的方法来获得浏览器版本

navigator.userAgent.split(')').reverse()[0].match(/(?!Gecko|Version|[A-Za-z]+?Web[Kk]it)[A-Z][a-z]+\/[\d.]+/g)[0].split('/')

样例输出:

Firefox/39.0