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


当前回答

这个小图书馆可能对你有帮助。但是请注意,浏览器检测并不总是解决方案。

其他回答

遗憾的是,IE11的导航器中不再有MSIE。

Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; OfficeLiveConnector.1.5; OfficeLivePatch.1.3; .NET4.0C; BRI/2; BOIE9;ENUS; rv:11.0) like Gecko

至于为什么你想知道你在使用哪个浏览器,这是因为每个浏览器都有自己的一组错误,你最终实现了浏览器和版本特定的解决方案,或者告诉用户使用不同的浏览器!

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`

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

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

所有关于web浏览器的信息都包含在navigator对象中。名字和版本都在那里。

var appname = window.navigator.appName;

来源:javascript浏览器检测

var browser = navigator.appName;
var version = navigator.appVersion;

然而,请注意,两者并不一定反映事实。许多浏览器都可以设置为其他浏览器的掩码。例如,你不能总是确定用户是用IE6还是用伪装成IE6的Opera上网。

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

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

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

现在根据jQuery弃用。

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

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