慕少森
这结合了肯纳贝克(K)的答案和Hermann Ingjaldsson(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.}