如何检测浏览器的版本?


286

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

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


6
我建议设置在经过验证的库中,而不要使用小块代码:* github.com/bestiejs/platform.js * github.com/ded/bowser都具有> 1,000星
Simon Fakir

您可以使用UAParser JavaScript库来检测浏览器及其版本。我是按照以下方法进行操作的:如何使用JavaScript检测浏览器,引擎,操作系统,CPU和设备?
卢赞·巴拉

Answers:


504

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

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`


2
刚刚发现严重问题,将浏览器IE11降级为IE10导航用户代理,显示Mozilla / 4.0(兼容; MSIE 7.0; Windows NT 6.1; WOW64; Trident / 6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E)从带有三叉戟/6.0的IE7字符串中小心
Yogesh

倒数第二行M[1] = tem[1]不是M[2]吗?使用当前的代码,Opera 12.14用户代理字符串Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14返回结果Opera 9.80 12.14。海事组织,正确的结果将是Opera 12.14我的建议所能实现的。
Kirk Woll 2014年

58
如果此答案包括输出示例,将很有帮助。我不能告诉该函数期望什么字符串。
fourdogit 2014年

尚未考虑Edge:tem = ua.match(/\b(OPR|Edge)\/(\d+)/i); if (tem != null) return {name : tem[1] === 'OPR' ? 'Opera' : tem[1], version : tem[2]};
Vincent Ketelaars 2015年

6
该脚本错误地报告了内部Facebook浏览器的Chrome浏览器4.0版本(当您在Android上单击Facebook应用内的Web链接时启动)。useragent字符串看起来像:Mozilla/5.0 (Linux; Android 5.0; Nexus 9 Build/LRX21R; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/45.0.2454.95 Safari/537.36 [FB_IAB/FB4A;FBAV/50.0.0.10.54;]不幸的是,这是一个非常杰出的用户代理,因此不能真正忽略它……
Willster 2015年

205

这是对肯纳贝克答案的改进。

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);

这样,您可以保护自己免受代码晦涩的困扰。


(某些平台-例如os x-将为navigator.userAgent提供不同的输出,并且您无法通过'Opera'字符串而不是'OPR'识别Opera浏览器。)
Trainoasis 2014年

如果tem!= null,则get_browser和get_browser_version在'if trident'和'if chrome'条件条件内返回错误的详细信息
Pixelthis 2014年

53

这结合了肯尼贝克(K)的答案和赫尔曼·英杰兹森(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.
}

45

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

lancedikson开发的Bowser -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/bowser@2.4.0/es5.js"></script>

*支持基于Chromium的Edge


bestiejs的Platform.js -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>

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>

darcyclarke的Detect.js(已存档) -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>

由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>


重要说明:

  • whichBrowser -1,355★s-最后更新于2018年10月2日
  • Modernizr -23,397★s-最后更新于2019年1月12日-要喂饱一匹马,特征检测应该会引发任何canIuse样式问题。浏览器检测实际上仅用于为各个浏览器提供自定义图像,下载文件或说明。

进一步阅读


29

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

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

它似乎维护得很好。



16

我一直在寻找自己的解决方案,因为jQuery 1.9.1及更高版本已删除了该$.browser功能。我想出了这个对我有用的小功能。它确实需要一个全局变量(我称为mine _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;
}

要检查当前浏览器是否为Opera,您可以执行以下操作

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

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

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


1
对于Windows 10中的新IE Edge(aka Spartan),它表明我的浏览器是Chrome 42-用户代理字符串:mozilla / 5.0(windows nt 10.0; win64; x64)applewebkit / 537.36(khtml,如gecko)chrome / 42.0 .2311.135 safari / 537.36 edge / 12.10240浏览器是chrome 42
Rulisp 2015年

1
感谢@Rulisp的评论,并提供了示例uagent,因为我没有Edge或Win10。从它开始,我已经更新了jsFiddle中的代码以反映这一点。如果您想使用样本uagent进行测试,就给我一把小提琴。让我知道是否有问题。
Danail Gabenski 2015年

13
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;
}

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


9

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

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

编辑:正如Joshua在下面的评论中所写,自1.9版本以来,jQuery已不再支持jQuery.browser属性(有关更多详细信息,请参阅jQuery 1.9发行说明)。jQuery开发团队建议使用更完整的方法,例如使用Modernizr库修改UI 。


16
jQuery 1.9删除了对$ .browser的支持,因此不再是一个选择。
约书亚

约书亚-是的,你是对的;至少他们离开了jQuery.support属性,以检测浏览器对某些功能的支持(但我不确定这是否是最初的问题)
Marek 2013年

7

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

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

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

参见工作示例→


4

navigator.userAgent- Firefox/xxx.xxx.xxx在最后指定。


4
<script type="text/javascript">
var version = navigator.appVersion;
alert(version);
</script>

4

我根据Hermann Ingjaldsson的回答编写了一个版本检测器,但它更健壮,并且它返回其中包含名称/版本数据的对象。它涵盖了主要的浏览器,但我不必为过多的移动浏览器和次要浏览器而烦恼:

function getBrowserData(nav) {
    var data = {};

    var ua = data.uaString = nav.userAgent;
    var browserMatch = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
    if (browserMatch[1]) { browserMatch[1] = browserMatch[1].toLowerCase(); }
    var operaMatch = browserMatch[1] === 'chrome';
    if (operaMatch) { operaMatch = ua.match(/\bOPR\/([\d\.]+)/); }

    if (/trident/i.test(browserMatch[1])) {
        var msieMatch = /\brv[ :]+([\d\.]+)/g.exec(ua) || [];
        data.name = 'msie';
        data.version = msieMatch[1];
    }
    else if (operaMatch) {
        data.name = 'opera';
        data.version = operaMatch[1];
    }
    else if (browserMatch[1] === 'safari') {
        var safariVersionMatch = ua.match(/version\/([\d\.]+)/i);
        data.name = 'safari';
        data.version = safariVersionMatch[1];
    }
    else {
        data.name = browserMatch[1];
        data.version = browserMatch[2];
    }

    var versionParts = [];
    if (data.version) {
        var versionPartsMatch = data.version.match(/(\d+)/g) || [];
        for (var i=0; i < versionPartsMatch.length; i++) {
            versionParts.push(versionPartsMatch[i]);
        }
        if (versionParts.length > 0) { data.majorVersion = versionParts[0]; }
    }
    data.name = data.name || '(unknown browser name)';
    data.version = {
        full: data.version || '(unknown full browser version)',
        parts: versionParts,
        major: versionParts.length > 0 ? versionParts[0] : '(unknown major browser version)'
    };

    return data;
};

然后可以像这样使用:

var brData = getBrowserData(window.navigator || navigator);
console.log('name: ' + brData.name);
console.log('major version: ' + brData.version.major);
// etc.

3
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName  = navigator.appName;
var fullVersion  = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;

// In Opera, the true version is after "Opera" or after "Version"

if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+6);
 if ((verOffset=nAgt.indexOf("Version"))!=-1)
   fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent

else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
 browserName = "Microsoft Internet Explorer";
 fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"

else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"

else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
 browserName = "Safari";
 fullVersion = nAgt.substring(verOffset+7);
 if ((verOffset=nAgt.indexOf("Version"))!=-1)
   fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"

else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
 browserName = "Firefox";
 fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent

else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
          (verOffset=nAgt.lastIndexOf('/')) )
{
 browserName = nAgt.substring(nameOffset,verOffset);
 fullVersion = nAgt.substring(verOffset+1);
 if (browserName.toLowerCase()==browserName.toUpperCase()) {
  browserName = navigator.appName;
 }
}

// trim the fullVersion string at semicolon/space if present

if ((ix=fullVersion.indexOf(";"))!=-1)
   fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
   fullVersion=fullVersion.substring(0,ix);

majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
 fullVersion  = ''+parseFloat(navigator.appVersion);
 majorVersion = parseInt(navigator.appVersion,10);
}

document.write(''
 +'Browser name  = '+browserName+'<br>'
 +'Full version  = '+fullVersion+'<br>'
 +'Major version = '+majorVersion+'<br>'
 +'navigator.appName = '+navigator.appName+'<br>'
 +'navigator.userAgent = '+navigator.userAgent+'<br>'
)

在此处查看演示。.http://jsfiddle.net/hw4jM/3/


2

我已经用ASP代码制作了一个脚本来检测浏览器,浏览器版本,操作系统和操作系统版本。我在ASP中执行此操作的原因是因为我要将数据存储在日志数据库中。因此,我不得不检测浏览器服务器端。

这是代码:

on error resume next
ua = lcase(Request.ServerVariables("HTTP_USER_AGENT"))
moz = instr(ua,"mozilla")  
ffx = instr(ua,"firefox")  
saf = instr(ua,"safari")
crm = instr(ua,"chrome") 
max = instr(ua,"maxthon") 
opr = instr(ua,"opera")
ie4 = instr(ua,"msie 4") 
ie5 = instr(ua,"msie 5") 
ie6 = instr(ua,"msie 6") 
ie7 = instr(ua,"msie 7") 
ie8 = instr(ua,"trident/4.0")
ie9 = instr(ua,"trident/5.0")

if moz>0 then 
    BrowserType = "Mozilla"
    BrVer = mid(ua,moz+8,(instr(moz,ua," ")-(moz+8)))
end if
if ffx>0 then 
    BrowserType = "FireFox"
    BrVer = mid(ua,ffx+8)
end if
if saf>0 then 
    BrowserType = "Safari"
    BrVerPlass = instr(ua,"version")
    BrVer = mid(ua,BrVerPlass+8,(instr(BrVerPlass,ua," ")-(BrVerPlass+8)))
end if
if crm>0 then 
    BrowserType = "Chrome"
    BrVer = mid(ua,crm+7,(instr(crm,ua," ")-(crm+7)))
end if
if max>0 then 
    BrowserType = "Maxthon"
    BrVer = mid(ua,max+8,(instr(max,ua," ")-(max+8)))
end if
if opr>0 then 
    BrowserType = "Opera"
    BrVerPlass = instr(ua,"presto")
    BrVer = mid(ua,BrVerPlass+7,(instr(BrVerPlass,ua," ")-(BrVerPlass+7)))
end if
if ie4>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "4"
end if
if ie5>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "5"
end if
if ie6>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "6"
end if
if ie7>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "7"
end if
if ie8>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "8"
    if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
end if
if ie9>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "9"
    if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
    if ie8>0 then BrVer = BrVer & " (in IE8 compability mode)"
end if

OSSel = mid(ua,instr(ua,"(")+1,(instr(ua,";")-instr(ua,"("))-1)
OSver = mid(ua,instr(ua,";")+1,(instr(ua,")")-instr(ua,";"))-1)

if BrowserType = "Internet Explorer" then
    OSStart = instr(ua,";")
    OSStart = instr(OSStart+1,ua,";")        
    OSStopp = instr(OSStart+1,ua,";")
    OSsel = mid(ua,OSStart+2,(OSStopp-OSStart)-2)
end if

    Select case OSsel
        case "windows nt 6.1"
            OS = "Windows"
            OSver = "7"
        case "windows nt 6.0"
            OS = "Windows"
            OSver = "Vista"
        case "windows nt 5.2"
            OS = "Windows"
            OSver = "Srv 2003 / XP x64"
        case "windows nt 5.1"
            OS = "Windows"
            OSver = "XP"
        case else
            OS = OSSel
    End select

Response.write "<br>" & ua & "<br>" & BrowserType & "<br>" & BrVer & "<br>" & OS & "<br>" & OSver & "<br>"

'Use the variables here for whatever you need........

2

该页面似乎有一个不错的片段,该片段仅使用appString和appVersion属性作为最后的手段,因为它声称它们在某些浏览器中不可靠。页面上的代码如下:

var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName  = navigator.appName;
var fullVersion  = ''+parseFloat(navigator.appVersion); 
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;

// In Opera 15+, the true version is after "OPR/" 
if ((verOffset=nAgt.indexOf("OPR/"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+4);
}
// In older Opera, the true version is after "Opera" or after "Version"
else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+6);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
 browserName = "Microsoft Internet Explorer";
 fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome" 
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version" 
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
 browserName = "Safari";
 fullVersion = nAgt.substring(verOffset+7);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox" 
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
 browserName = "Firefox";
 fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent 
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < 
          (verOffset=nAgt.lastIndexOf('/')) ) 
{
 browserName = nAgt.substring(nameOffset,verOffset);
 fullVersion = nAgt.substring(verOffset+1);
 if (browserName.toLowerCase()==browserName.toUpperCase()) {
  browserName = navigator.appName;
 }
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
   fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
   fullVersion=fullVersion.substring(0,ix);

majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
 fullVersion  = ''+parseFloat(navigator.appVersion); 
 majorVersion = parseInt(navigator.appVersion,10);
}

document.write(''
 +'Browser name  = '+browserName+'<br>'
 +'Full version  = '+fullVersion+'<br>'
 +'Major version = '+majorVersion+'<br>'
 +'navigator.appName = '+navigator.appName+'<br>'
 +'navigator.userAgent = '+navigator.userAgent+'<br>'
)

2

添加我自己的Hermann答案实现。我需要操作系统检测,因此已添加。还包括一些您可能需要进行ES5-修改的ES6代码(因为我们有一个转译器)。

detectClient() {
    let nav = navigator.appVersion,
        os = 'unknown',
        client = (() => {
            let agent = navigator.userAgent,
                engine = agent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
                build;

            if(/trident/i.test(engine[1])){
                build = /\brv[ :]+(\d+)/g.exec(agent) || [];
                return {browser:'IE', version:(build[1] || '')};
            }

            if(engine[1] === 'Chrome'){
                build = agent.match(/\bOPR\/(\d+)/);

                if(build !== null) {
                    return {browser: 'Opera', version: build[1]};
                }
            }

            engine = engine[2] ? [engine[1], engine[2]] : [navigator.appName, nav, '-?'];

            if((build = agent.match(/version\/(\d+)/i)) !== null) {
                engine.splice(1, 1, build[1]);
            }

            return {
              browser: engine[0],
              version: engine[1]
            };
        })();

    switch (true) {
        case nav.indexOf('Win') > -1:
            os = 'Windows';
        break;
        case nav.indexOf('Mac') > -1:
            os = 'MacOS';
        break;
        case nav.indexOf('X11') > -1:
            os = 'UNIX';
        break;
        case nav.indexOf('Linux') > -1:
            os = 'Linux';
        break;
    }        

    client.os = os;
    return client;
}

返回值: Object {browser: "Chrome", version: "50", os: "UNIX"}


2

我想分享我为解决此问题而编写的这段代码。对我来说,它已经在大多数主流浏览器中进行了测试,并且就像一个魅力一样!

似乎该代码与其他答案非常相似,但已对其进行了修改,以便我可以在最近错过的jquery中使用它插入浏览器对象,当然,它是上述代码的组合,与我所做的部分:

(function($, ua){

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

if(/trident/i.test(M[1])){
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    res = 'IE ' + (tem[1] || '');
}
else if(M[1] === 'Chrome'){
    tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
    if(tem != null) 
        res = tem.slice(1).join(' ').replace('OPR', 'Opera');
    else
        res = [M[1], M[2]];
}
else {
    M = M[2]? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if((tem = ua.match(/version\/(\d+)/i)) != null) M = M.splice(1, 1, tem[1]);
    res = M;
}

res = typeof res === 'string'? res.split(' ') : res;

$.browser = {
    name: res[0],
    version: res[1],
    msie: /msie|ie/i.test(res[0]),
    firefox: /firefox/i.test(res[0]),
    opera: /opera/i.test(res[0]),
    chrome: /chrome/i.test(res[0]),
    edge: /edge/i.test(res[0])
}

})(typeof jQuery != 'undefined'? jQuery : window.$, navigator.userAgent);

 console.log($.browser.name, $.browser.version, $.browser.msie); 
// if IE 11 output is: IE 11 true

2

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`


1

我用它来获取实际浏览器版本的名称和编号(整数):

function getInfoBrowser() {
    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: 'Explorer', version: parseInt((tem[1] || '')) };
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
        if (tem != null) { let app = tem.slice(1).toString().split(','); return { name: app[0].replace('OPR', 'Opera'), version: parseInt(app[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: parseInt(M[1])
    };
}

function getBrowser(){
  let info = getInfoBrowser();
  $("#i-name").html(info.name);
  $("#i-version").html(info.version);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" onclick="getBrowser();" value="Get Info Browser"/>
<hr/>
Name: <span id="i-name"></span><br/>
Version: <span id="i-version"></span>

这个在

镀铬; 火狐; 苹果浏览器 ; Internet Explorer(> = 9);歌剧; 边缘

为了我。


1

这比@kennebec片段具有更好的兼容性;
将返回浏览器名称和版本(返回72而不是72.0.3626.96)。

在Safari,Chrome,Opera,Firefox,IE,Edge,UCBrowser和移动设备上进行了测试。

function browser() {
    var userAgent = navigator.userAgent,
        match = userAgent.match(/(opera|chrome|crios|safari|ucbrowser|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
        result = {},
        tem;

    if (/trident/i.test(match[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(userAgent) || [];
        result.name = "Internet Explorer";
    } else if (match[1] === "Chrome") {
        tem = userAgent.match(/\b(OPR|Edge)\/(\d+)/);

        if (tem && tem[1]) {
            result.name = tem[0].indexOf("Edge") === 0 ? "Edge" : "Opera";
        }
    }
    if (!result.name) {
        tem = userAgent.match(/version\/(\d+)/i); // iOS support
        result.name = match[0].replace(/\/.*/, "");

        if (result.name.indexOf("MSIE") === 0) {
            result.name = "Internet Explorer";
        }
        if (userAgent.match("CriOS")) {
            result.name = "Chrome";
        }

    }
    if (tem && tem.length) {
        match[match.length - 1] = tem[tem.length - 1];
    }

    result.version = Number(match[match.length - 1]);

    return result;
}

0
var ua = navigator.userAgent;

if (/Firefox\//.test(ua))
   var Firefox = /Firefox\/([0-9\.A-z]+)/.exec(ua)[1];

0

我写这是为了我的需要。

它会获取信息,例如是移动设备还是视网膜显示器

尝试一下

var nav = {
        isMobile:function(){
            return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) != null);
        },
        isDesktop:function(){
            return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) == null);
        },
        isAndroid: function() {
            return navigator.userAgent.match(/Android/i);
        },
        isBlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        isIOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        isOpera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        isWindows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        isRetina:function(){
            return window.devicePixelRatio && window.devicePixelRatio > 1;
        },
        isIPad:function(){
            isIPad = (/ipad/gi).test(navigator.platform);
            return isIPad;
        },
        isLandscape:function(){
            if(window.innerHeight < window.innerWidth){
                return true;
            }
            return false;
        },
        getIOSVersion:function(){
            if(this.isIOS()){
                var OSVersion = navigator.appVersion.match(/OS (\d+_\d+)/i);
                OSVersion = OSVersion[1] ? +OSVersion[1].replace('_', '.') : 0;
                return OSVersion;
            }
            else
                return false;
        },
        isStandAlone:function(){
            if(_.is(navigator.standalone))
                return navigator.standalone;
            return false;
        },
        isChrome:function(){
            var isChrome = (/Chrome/gi).test(navigator.appVersion);
            var isSafari = (/Safari/gi).test(navigator.appVersion)
            return isChrome && isSafari;
        },
        isSafari:function(){
            var isSafari = (/Safari/gi).test(navigator.appVersion)
            var isChrome = (/Chrome/gi).test(navigator.appVersion)
            return !isChrome && isSafari;
        }
}

0

对于任何使用angular的PWA应用程序,您可以在index.html的主体部分中放置代码来检查是否支持浏览器-

<body>
    <div id="browser"></div>
    <script>
        var operabrowser = true;
        operabrowser = (navigator.userAgent.indexOf('Opera Mini') > -1);
        if (operabrowser) {
            txt = "<p>Browser not supported use different browser...</p>";
            document.getElementById("browser").innerHTML = txt;
        }
    </script>
</body>

-1

这是某人的Java版本,该人想使用在服务器端使用String返回 HttpServletRequest.getHeader("User-Agent");

我正在测试70种不同的浏览器配置。

public static String decodeBrowser(String userAgent) {
    userAgent= userAgent.toLowerCase();
    String name = "unknown";
    String version = "0.0";
    Matcher userAgentMatcher = USER_AGENT_MATCHING_PATTERN.matcher(userAgent);
    if (userAgentMatcher.find()) {
      name = userAgentMatcher.group(1);
      version = userAgentMatcher.group(2);
      if ("trident".equals(name)) {
        name = "msie";
        Matcher tridentVersionMatcher = TRIDENT_MATCHING_PATTERN.matcher(userAgent);
        if (tridentVersionMatcher.find()) {
          version = tridentVersionMatcher.group(1);
        }
      }
    }
    return name + " " + version;
  }

  private static final Pattern USER_AGENT_MATCHING_PATTERN=Pattern.compile("(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*([\\d\\.]+)");
  private static final Pattern TRIDENT_MATCHING_PATTERN=Pattern.compile("\\brv[ :]+(\\d+(\\.\\d+)?)");

-1
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = '' + parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion, 10);
var nameOffset, verOffset, ix;

// In Opera 15+, the true version is after "OPR/" 
if ((verOffset = nAgt.indexOf("OPR/")) != -1) {
    browserName = "Opera";
    fullVersion = nAgt.substring(verOffset + 4);
}
// In older Opera, the true version is after "Opera" or after "Version"
else if ((verOffset = nAgt.indexOf("Opera")) != -1) {
    browserName = "Opera";
    fullVersion = nAgt.substring(verOffset + 6);
    if ((verOffset = nAgt.indexOf("Version")) != -1)
        fullVersion = nAgt.substring(verOffset + 8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
    browserName = "Microsoft Internet Explorer";
    fullVersion = nAgt.substring(verOffset + 5);
}
// In Chrome, the true version is after "Chrome" 
else if ((verOffset = nAgt.indexOf("Chrome")) != -1) {
    browserName = "Google Chrome";
    fullVersion = nAgt.substring(verOffset + 7);
}
// In Safari, the true version is after "Safari" or after "Version" 
else if ((verOffset = nAgt.indexOf("Safari")) != -1) {
    browserName = "Safari";
    fullVersion = nAgt.substring(verOffset + 7);
    if ((verOffset = nAgt.indexOf("Version")) != -1)
        fullVersion = nAgt.substring(verOffset + 8);
}
// In Firefox, the true version is after "Firefox" 
else if ((verOffset = nAgt.indexOf("Firefox")) != -1) {
    browserName = "Mozilla Firefox";
    fullVersion = nAgt.substring(verOffset + 8);
}
// In most other browsers, "name/version" is at the end of userAgent 
else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
    browserName = nAgt.substring(nameOffset, verOffset);
    fullVersion = nAgt.substring(verOffset + 1);
    if (browserName.toLowerCase() == browserName.toUpperCase()) {
        browserName = navigator.appName;
    }
}
// trim the fullVersion string at semicolon/space if present
if ((ix = fullVersion.indexOf(';')) != -1) fullVersion = fullVersion.substring(0, ix);
if ((ix = fullVersion.indexOf(' ')) != -1) fullVersion = fullVersion.substring(0, ix);

majorVersion = parseInt('' + fullVersion, 10);
if (isNaN(majorVersion)) {
    fullVersion = '' + parseFloat(navigator.appVersion);
    majorVersion = parseInt(navigator.appVersion, 10);
}

2
您能否在代码中加上一些代码说明?
Yogesh Sharma's
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.