Javascript 如何检测浏览器的版本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5916900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:30:42  来源:igfitidea点击:

How can you detect the version of a browser?

javascriptbrowserversionbrowser-detection

提问by odle

I've been searching around for code that would let me detect if the user visiting the website has Firefox 3 or 4. All I have found is code to detect the type of browser but not the version.

我一直在寻找可以让我检测访问网站的用户是否使用 Firefox 3 或 4 的代码。我找到的只是检测浏览器类型而不是版本的代码。

How can I detect the version of a browser like this?

如何检测这样的浏览器版本?

回答by kennebec

You can see what the browser says, and use that information for logging or testing multiple browsers.

您可以查看浏览器所说的内容,并使用该信息记录或测试多个浏览器。

navigator.sayswho= (function(){
    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(' ');
})();

console.log(navigator.sayswho); // outputs: `Chrome 62`

回答by Hermann Ingjaldsson

This is an improvement on Kennebec's answer.

这是对 Kennebec 答案的改进。

function get_browser() {
    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 {name:'IE',version:(tem[1]||'')};
        }   
    if(M[1]==='Chrome'){
        tem=ua.match(/\bOPR|Edge\/(\d+)/)
        if(tem!=null)   {return {name:'Opera', version:tem[1]};}
        }   
    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 {
      name: M[0],
      version: M[1]
    };
 }

var browser=get_browser(); // browser.name = 'Chrome'
                           // browser.version = '40'

console.log(browser);

This way you can shield yourself from the obscurity of the code.

通过这种方式,您可以避免代码的晦涩。

回答by Brandon

This combines kennebec's (K) answer with Hermann Ingjaldsson's (H) answer:

这结合了 kennebec (K) 的回答和 Hermann Ingjaldsson 的 (H) 回答:

  • Maintains original answer's minimal code. (K)
  • Works with Microsoft Edge (K)
  • Extends the navigator object instead of creating a new variable/object. (K)
  • Separates browser version and name into independent child objects. (H)
  • 保持原始答案的最小代码。(K)
  • 适用于 Microsoft Edge (K)
  • 扩展导航器对象而不是创建新的变量/对象。(K)
  • 将浏览器版本和名称分成独立的子对象。(H)

 

 

navigator.browserSpecs = (function(){
    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 {name:'IE',version:(tem[1] || '')};
    }
    if(M[1]=== 'Chrome'){
        tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem != null) return {name:tem[1].replace('OPR', 'Opera'),version:tem[2]};
    }
    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 {name:M[0], version:M[1]};
})();

console.log(navigator.browserSpecs); //Object { name: "Firefox", version: "42" }

if (navigator.browserSpecs.name == 'Firefox') {
    // Do something for Firefox.
    if (navigator.browserSpecs.version > 42) {
        // Do something for Firefox versions greater than 42.
    }
}
else {
    // Do something for all other browsers.
}

回答by KyleMit

Here are several prominent libraries that handle browser detection as of May 2019.

以下是截至 2019 年 5 月处理浏览器检测的几个著名库。

Bowserby lancedikson - 3,761★s - Last updated May 26, 2019 - 4.8KB

Bowserby lancedikson - 3,761★s - 最后更新于 2019 年 5 月 26 日 - 4.8KB

var result = bowser.getParser(window.navigator.userAgent);
console.log(result);
document.write("You are using " + result.parsedResult.browser.name +
               " v" + result.parsedResult.browser.version + 
               " on " + result.parsedResult.os.name);
<script src="https://unpkg.com/[email protected]/es5.js"></script>

*supports Edge based on Chromium

*支持基于 Chromium 的 Edge



Platform.jsby bestiejs - 2,250★s - Last updated Oct 30, 2018 - 5.9KB

平台.js by bestiejs - 2,250★s - 最后更新于 2018 年 10 月 30 日 - 5.9KB

console.log(platform);
document.write("You are using " + platform.name +
               " v" + platform.version + 
               " on " + platform.os);
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>

jQuery Browserby gabceb - 504★s - Last updated Nov 23, 2015 - 1.3KB

gabceb 的jQuery 浏览器- 504★s - 最后更新于 2015 年 11 月 23 日 - 1.3KB

console.log($.browser)
document.write("You are using " + $.browser.name +
               " v" + $.browser.versionNumber + 
               " on " + $.browser.platform);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>

Detect.js (Archived)by darcyclarke - 522★s - Last updated Oct 26, 2015 - 2.9KB

Detect.js (Archived)by darcyclarke - 522★s - 最后更新于 2015 年 10 月 26 日 - 2.9KB

var result = detect.parse(navigator.userAgent);
console.log(result);
document.write("You are using " + result.browser.family +
               " v" + result.browser.version + 
               " on " + result.os.family);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>

Browser Detect (Archived)by QuirksMode - Last updated Nov 14, 2013 - 884B

浏览器检测(存档)由 QuirksMode - 最后更新于 2013 年 11 月 14 日 - 884B

console.log(BrowserDetect)
document.write("You are using " + BrowserDetect.browser +
               " v" + BrowserDetect.version + 
               " on " + BrowserDetect.OS);
<script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>



Notable Mentions:

值得注意的提及:

  • WhichBrowser- 1,355★s - Last updated Oct 2, 2018
  • Modernizr- 23,397★s - Last updated Jan 12, 2019 - To feed a fed horse, feature detection should drive any canIusestyle questions. Browser detection is really just for providing customized images, download files, or instructions for individual browsers.
  • 哪个浏览器- 1,355★s - 最后更新于 2018 年 10 月 2 日
  • Modernizr- 23,397★s - 最后更新于 2019 年 1 月 12 日 - 为了喂饱喂饱的马,特征检测应该驱动任何canIuse风格的问题。浏览器检测实际上只是为单个浏览器提供自定义图像、下载文件或说明。

Further Reading

进一步阅读

回答by Michael Cole

The bowserJavaScript library offers this functionality.

库巴JavaScript库提供了这个功能。

if (bowser.msie && bowser.version <= 6) {
  alert('Hello China');
}

It seems to be well maintained.

它似乎维护得很好。

回答by Oliver Moran

Use this: http://www.quirksmode.org/js/detect.html

使用这个:http: //www.quirksmode.org/js/detect.html

alert(BrowserDetect.browser); // will say "Firefox"
alert(BrowserDetect.version); // will say "3" or "4"

回答by Danail Gabenski

I was looking for a solution for myself, since jQuery 1.9.1and above have removed the $.browserfunctionality. I came up with this little function that works for me. It does need a global variable (I've called mine _browser) in order to check which browser it is. I've written a jsfiddleto illustrate how it can be used, of course it can be expanded for other browsers by just adding a test for _browser.foo, where foo is the name of the browser. I did just the popular ones.

我一直在为自己寻找解决方案,因为jQuery 1.9.1及更高版本已删除该$.browser功能。我想出了这个对我有用的小功能。它确实需要一个全局变量(我称之为我的 _browser)来检查它是哪个浏览器。我已经写了一个jsfiddle来说明它是如何使用的,当然它可以通过为 _browser.foo 添加一个测试来扩展到其他浏览器,其中 foo 是浏览器的名称。我只做了流行的。

detectBrowser()

检测浏览器()

_browser = {};

function detectBrowser() {
  var uagent = navigator.userAgent.toLowerCase(),
      match = '';

  _browser.chrome  = /webkit/.test(uagent)  && /chrome/.test(uagent)      &&
                     !/edge/.test(uagent);

  _browser.firefox = /mozilla/.test(uagent) && /firefox/.test(uagent);

  _browser.msie    = /msie/.test(uagent)    || /trident/.test(uagent)     ||
                     /edge/.test(uagent);

  _browser.safari  = /safari/.test(uagent)  && /applewebkit/.test(uagent) &&
                     !/chrome/.test(uagent);

  _browser.opr     = /mozilla/.test(uagent) && /applewebkit/.test(uagent) &&
                     /chrome/.test(uagent)  && /safari/.test(uagent)      &&
                     /opr/.test(uagent);

  _browser.version = '';

  for (x in _browser) {
    if (_browser[x]) {

      match = uagent.match(
                new RegExp("(" + (x === "msie" ? "msie|edge" : x) + ")( |\/)([0-9]+)")
              );

      if (match) {
        _browser.version = match[3];
      } else {
        match = uagent.match(new RegExp("rv:([0-9]+)"));
        _browser.version = match ? match[1] : "";
      }
      break;
    }
  }
  _browser.opera = _browser.opr;
  delete _browser.opr;
}

To check if the current browser is Opera you would do

要检查当前浏览器是否为 Opera,您会这样做

if (_browser.opera) { // Opera specific code }

EditFixed the formatting, fixed the detection for IE11 and Opera/Chrome, changed to browserResult from result. Now the order of the _browserkeys doesn't matter. Updated jsFiddlelink.

编辑修复格式,修复IE11和Opera/Chrome的检测,结果改为browserResult。现在_browser键的顺序无关紧要。更新了jsFiddle链接。

2015/08/11EditAdded new testcase for Internet Explorer 12 (EDGE), fixed a small regexp problem. Updated jsFiddlelink.

2015/08/11 Edit为 Internet Explorer 12 (EDGE) 添加了新的测试用例,修复了一个小的正则表达式问题。更新了jsFiddle链接。

回答by Michael Bleidistel

function BrowserCheck()
{
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) {M[2]=tem[1];}
    M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
    return M;
}

This will return an array, first element is the browser name, second element is the complete version number in string format.

这将返回一个数组,第一个元素是浏览器名称,第二个元素是字符串格式的完整版本号。

回答by Marek

jQuery can handle this quite nice (jQuery.browser)

jQuery 可以很好地处理这个问题 ( jQuery.browser)

var ua = $.browser;
if ( ua.mozilla && ua.version.slice(0,3) == "1.9" ) {
    alert( "Do stuff for firefox 3" );
}

EDIT: As Joshua wrote in his comment below, jQuery.browserproperty is no longer supported in jQuery since version 1.9 (read jQuery 1.9 release notesfor more details). jQuery development team recommendsusing more complete approach like adapting UI with Modernizrlibrary.

编辑:正如 Joshua 在下面的评论中所写的那样,自 1.9 版以来,jQuery.browser属性不再受 jQuery 支持(阅读jQuery 1.9 发行说明了解更多详细信息)。jQuery 开发团队建议使用更完整的方法,例如使用Modernizr库调整 UI 。

回答by mVChr

In pure Javascript you can do a RegExp match on the navigator.userAgentto find the Firefox version:

在纯 Javascript 中,您可以在 上进行 RegExp 匹配navigator.userAgent以查找 Firefox 版本:

var uMatch = navigator.userAgent.match(/Firefox\/(.*)$/),
    ffVersion;
if (uMatch && uMatch.length > 1) {
    ffVersion = uMatch[1];
}

ffVersionwill be undefinedif not a Firefox browser.

ffVersionundefined如果不是 Firefox 浏览器,将是。

See working example →

参见工作示例 →