Javascript - 检测浏览器版本 [英] Javascript - detecting browser version
问题描述
我知道这不是最可靠的方式,但我真的没有太多其他选择.我基本上需要检测访问我网站的浏览器和版本.如果是某个浏览器/版本,它会显示一条消息.这是针对 TLS 问题,即某些浏览器版本不会显示 https 页面.
I know this is not the most reliable way, but I don't really have many other choices. I essentially need to detect what browser and version visits my website. If it is a certain browser/version, it will display a message. This is for the TLS issue, whereby certain browser versions will not display a https page.
无论如何,目前我有类似以下内容
Anyways, at the moment I have something like the following
function getBrowserInfo()
{
var ua = navigator.userAgent, tem,
M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1]))
{
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome')
{
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M = M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!= null)
M.splice(1, 1, tem[1]);
return M.join(' ');
}
var browserInfo = getBrowserInfo();
browserInfo = browserInfo.split(" ");
$(function () {
alert(browserInfo);
if(browserInfo[0] == 'Firefox' && browserInfo[1] < 27) {
alert("Firefox");
}
if(browserInfo[0] == 'Chrome' && browserInfo[1] < 22) {
alert("Chrome");
}
if(browserInfo[0] == 'IE' && browserInfo[1] < 11) {
alert("IE");
}
if(browserInfo[0] == 'Safari' && browserInfo[1] < 11) {
alert("Safari");
}
if(browserInfo[0] == 'Opera' && browserInfo[1] < 14) {
alert("Safari");
}
});
我关心的一件事是字符串的拆分,以防浏览器返回不同的格式.此外,我认为所有这些 if 语句都是多余的,但我想不出更有效的方法来做到这一点.
One thing that concerns me is the splitting of the string, incase a browser returns a different format. Additionally, I think all of these if statements are redundant, but I cant think of a more efficient way to do this.
基本上,我正在寻找有关检测浏览器及其版本的最佳方法的建议,以便我可以为该浏览器显示自定义消息.
Essentially, I am looking for advice as to the best way to detect a browser, and its version, so I can display a custom message for that browser.
谢谢
推荐答案
您似乎在使用 jQuery.您可以使用 $.browser 检测浏览器版本,但从 1.9.1 版本开始不推荐使用该功能.
It seems like you're using jQuery. You could detect the browser version using $.browser, but that feature is deprecated starting from version 1.9.1.
我建议使用这个 jQuery 插件,它支持浏览器类型 &版本检测:https://github.com/gabceb/jquery-browser-plugin
I would advise using this jQuery-plugin, which supports browser type & version detection: https://github.com/gabceb/jquery-browser-plugin
使用此插件,您可以使用此代码测试浏览器供应商:
Using this plugin, you can test for browser vendors using this code:
if($.browser.msie) {
alert('ie');
}
if($.browser.mozilla) {
alert('firefox');
}
...
如果您想检查浏览器的版本,可以使用以下代码:
If you would like to check for the version of the browser, you could use this code:
$.browser.version
这篇关于Javascript - 检测浏览器版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!