如何使用 JavaScript 检测浏览器版本和操作系统?

我已经尝试使用下面的代码,但它只显示在 Chrome 和 Mozilla 不能在 IE6中工作的结果。

<div id="example"></div>


<script type="text/javascript">


txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";


document.getElementById("example").innerHTML=txt;


</script>

产出:

Browser CodeName: Mozilla


Browser Name: Netscape


Browser Version: 5.0 (Windows)


Cookies Enabled: true


Platform: Win32


User-agent header: Mozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0

我需要得到的版本“火狐/12.0”只。

292325 次浏览

PPK 的剧本是这类事情的权威,正如@Jalpesh 所说,这可能会给你指出正确的方向

var wn = window.navigator,
platform = wn.platform.toString().toLowerCase(),
userAgent = wn.userAgent.toLowerCase(),
storedName;


// ie
if (userAgent.indexOf('msie',0) !== -1) {
browserName = 'ie';
os = 'win';
storedName = userAgent.match(/msie[ ]\d{1}/).toString();
version = storedName.replace(/msie[ ]/,'');


browserOsVersion = browserName + version;
}

取自 https://github.com/leopic/jquery.detectBrowser.js/blob/sans-jquery/jquery.detectBrowser.sansjQuery.js

检测浏览器的详细信息:

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

来源 JavaScript: 浏览器名称
请参阅 JSFiddle 以检测 Browser Details

检测操作系统:

// This script sets OSName variable as follows:
// "Windows"    for all versions of Windows
// "MacOS"      for all versions of Macintosh OS
// "Linux"      for all versions of Linux
// "UNIX"       for all other UNIX flavors
// "Unknown OS" indicates failure to detect the OS


var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";


document.write('Your OS: '+OSName);

来源 JavaScript: OS 检测
请参阅 JSFiddle 以检测 OS Details

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


// This script sets OSName variable as follows:
// "Windows"    for all versions of Windows
// "MacOS"      for all versions of Macintosh OS
// "Linux"      for all versions of Linux
// "UNIX"       for all other UNIX flavors
// "Unknown OS" indicates failure to detect the OS
    

var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
    

document.write('Your OS: '+OSName);

火狐浏览器、 Chrome 浏览器、 Opera 浏览器、 Internet Explorer 浏览器和 Safari 浏览器

var ua="Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1)";
//ua = navigator.userAgent;
var b;
var browser;
if(ua.indexOf("Opera")!=-1) {


b=browser="Opera";
}
if(ua.indexOf("Firefox")!=-1 && ua.indexOf("Opera")==-1) {
b=browser="Firefox";
// Opera may also contains Firefox
}
if(ua.indexOf("Chrome")!=-1) {
b=browser="Chrome";
}
if(ua.indexOf("Safari")!=-1 && ua.indexOf("Chrome")==-1) {
b=browser="Safari";
// Chrome always contains Safari
}


if(ua.indexOf("MSIE")!=-1 && (ua.indexOf("Opera")==-1 && ua.indexOf("Trident")==-1)) {
b="MSIE";
browser="Internet Explorer";
//user agent with MSIE and Opera or MSIE and Trident may exist.
}


if(ua.indexOf("Trident")!=-1) {
b="Trident";
browser="Internet Explorer";
}


// now for version




var version=ua.match(b+"[ /]+[0-9]+(.[0-9]+)*")[0];


console.log("broswer",browser);
console.log("version",version);

试试这个。

// Browser with version  Detection
navigator.sayswho= (function(){
var N= navigator.appName, ua= navigator.userAgent, tem;
var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\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;
})();


var browser_version          = navigator.sayswho;
alert("Welcome to " + browser_version);

检查工作小提琴(给你)

更新

我对 Platform.js(演示在这里)有一些很好的经验,但仍然建议要谨慎:

原文

我想向您推荐《 哪个浏览器: 每个人都会撒谎》的作者。

基本上,没有哪个浏览器是诚实的。无论你是使用 Chrome 还是 IE 浏览器,它们都会告诉你它们是支持 Gecko 和 Safari 的“ Mozilla Netscape”。你可以自己试试这个帖子里的任何一个小提琴:

他的小提琴

哈里哈兰的小提琴

或者其他任何东西... ... 用 Chrome 试试(可能还会成功) ,然后用最新版本的 IE 试试,你会哭的。当然,有一些启发式的方法,可以把它们都做好,但是要掌握所有的边缘情况是很乏味的,而且它们很可能在一年的时间内就不再起作用了。

以你的代码为例:

<div id="example"></div>
<script type="text/javascript">
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>

Chrome 表示:

浏览器代码: Mozilla

浏览器名称: Netscape

浏览器版本: 5.0(Windows NT 6.1; WOW64) AppleWebKit/537.36 Chrome/40.0.2214.115 Safari/537.36

启用 Cookies: true

平台: Win32

User-agent header: Mozilla/5.0(Windows NT 6.1; WOW64) AppleWebKit/537.36(KHTML,like Gecko) Chrome/40.0.2214.115 Safari/537.36

IE 表示:

浏览器代码: Mozilla

浏览器名称: Netscape

浏览器版本: 5.0(Windows NT 6.1; WOW64; Trident/7.0; SLCC2; . NET . NET CLR 3.5.30729; . NET CLR 3.0.30729; Media Center PC 6.0; . NET4.0 C; . NET4.0 E; InfoPath.3; rv: 11.0)类似于 Gecko

启用 Cookies: true

平台: Win32

用户代理头: Mozilla/5.0(Windows NT 6.1; WOW64; Trident/7.0; . NET CLR 2.0.50727; . NET CLR 3.5.30729; . NET CLR 3.0.30729; Media Center PC 6.0; . NET4.0 C; . NET4.0 E; InfoPath.3; rv: 11.0) like 壁虎

至少 Chrome 还有一个包含“ Chrome”和确切版本号的字符串。但是,对于 IE,你必须从它所支持的东西中推断出实际的版本号(还有谁会吹嘘他们支持 .NET或者 Media Center: P) ,然后将它与最后的 rv:进行匹配来得到版本号。当然,即使是这种复杂的启发式方法也很可能在 IE12(或者他们想叫它什么)出来时就失败了。

有一个用于此目的的库: https://github.com/bestiejs/platform.js#readme

那么你可以这样使用它

// example 1
platform.os; // 'Windows Server 2008 R2 / 7 x64'


// example 2 on an iPad
platform.os; // 'iOS 5.0'


// you can also access on the browser and some other properties
platform.name; // 'Safari'
platform.version; // '5.1'
platform.product; // 'iPad'
platform.manufacturer; // 'Apple'
platform.layout; // 'WebKit'


// or use the description to put all together
platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)'

要使用 JavaScript 检测操作系统,最好使用 UserAgent 代替了 Navator.appVersion

{
var OSName = "Unknown OS";
if (navigator.userAgent.indexOf("Win") != -1) OSName = "Windows";
if (navigator.userAgent.indexOf("Mac") != -1) OSName = "Macintosh";
if (navigator.userAgent.indexOf("Linux") != -1) OSName = "Linux";
if (navigator.userAgent.indexOf("Android") != -1) OSName = "Android";
if (navigator.userAgent.indexOf("like Mac") != -1) OSName = "iOS";
console.log('Your OS: ' + OSName);
}

我无法用同样的代码在 Chrome、 Firefox、 IE11和 Edge 上找到其他一些答案。 我想出了下面的方法,它似乎适用于上面列出的那些浏览器。我还想看看用户使用的是什么操作系统。我还没有使用用户覆盖的 User-Agent 设置在浏览器上测试过这一点,所以里程可能会有所不同。IF 的顺序对于正确工作非常重要。

let os, osStore, bStore, appVersion, browser;
// Chrome
if(navigator.vendor === "Google Inc."){
appVersion = navigator.appVersion.split(" ");
os = [appVersion[1],appVersion[2],appVersion[3],appVersion[4],appVersion[5]].join(" ");
os = os.split("(")[1].split(")")[0]
browser = appVersion[appVersion.length-2].split("/").join(" ");
console.log("Browser:",browser,"- OS:",os);
}


// Safari
else if(navigator.vendor === "Apple Computer, Inc."){
appVersion = navigator.appVersion.split(" ");
os = [appVersion[1],appVersion[2],appVersion[3],appVersion[4],appVersion[5]].join(" ");
os = os.split("(")[1].split(")")[0];
browser = appVersion[appVersion.length-1].split("/").join(" ");
console.log("Browser:",browser,"- OS:",os);
}


// Firefox is seems the only browser with oscpu
else if(navigator.oscpu){
bStore = navigator.userAgent.split("; ").join("-").split(" ");
browser = bStore[bStore.length-1].replace("/"," ");
osStore = [bStore[1],bStore[2],bStore[3]].join(" ");
osStore = osStore.split("-");
osStore.pop(osStore.lastIndexOf)
osStore = osStore.join(" ").split("(");
os = osStore[1];
console.log("Browser:",browser,"- OS:",os);
}


// IE is seems the only browser with cpuClass
// MSIE 11:10 Mode
else if(navigator.appName === "Microsoft Internet Explorer"){
bStore = navigator.appVersion.split("; ");
browser = bStore[1]+" / "+bStore[4].replace("/"," ");
os = [bStore[2],bStore[3]].join(" ");
console.log("Browser:",browser,"- OS:",os);
}


// MSIE 11
else if(navigator.cpuClass){
bStore = navigator.appVersion.split("; ");
osStore = [bStore[0],bStore[1]].join(" ");
os = osStore.split("(")[1];
browser = "MSIE 11 "+bStore[2].split("/").join(" ");
console.log("Browser:",browser,"- OS:",os);
}


// Edge
else if(navigator.appVersion){
browser = navigator.appVersion.split(" ");
browser = browser[browser.length -1].split("/").join(" ");
os = navigator.appVersion.split(")")[0].split("(")[1];
console.log("Browser:",browser,"- OS:",os);
}


// Other browser
else {
console.log(JSON.stringify(navigator));
}

检测用户 操作系统的代码

let os = navigator.userAgent.slice(13).split(';')
os = os[0]
console.log(os)
Windows NT 10.0

要获得基于 Mozilla 核心的新 Microsoft Edge,请添加:

else if ((verOffset=nAgt.indexOf("Edg"))!=-1) {
browserName = "Microsoft Edge";
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);
}

为此目的有3个库。你可以在线比较它们 https://www.whatsmyua.info(在不同的浏览器和设备中加载这个页面)并选择最适合你需要的。

  1. 用于 platform.js 的例子
<script src="platform.js"></script>
// on an iPad
platform.name; // 'Safari'
platform.version; // '5.1'
platform.product; // 'iPad'
platform.manufacturer; // 'Apple'
platform.layout; // 'WebKit'
platform.os; // 'iOS 5.0'
platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)'


// or parsing a given UA string
var info = platform.parse('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7.2; en; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 11.52');
info.name; // 'Opera'
info.version; // '11.52'
info.layout; // 'Presto'
info.os; // 'Mac OS X 10.7.2'
info.description; // 'Opera 11.52 (identifying as Firefox 4.0) on Mac OS X 10.7.2'
  1. Ua-parser.js 的用法示例
<script src="ua-parser.min.js"></script>
var parser = new UAParser();
console.log(parser.getResult());
/*
/// This will print an object structured like this:
{
ua: "",
browser: {
name: "",
version: "",
major: "" //@deprecated
},
engine: {
name: "",
version: ""
},
os: {
name: "",
version: ""
},
device: {
model: "",
type: "",
vendor: ""
},
cpu: {
architecture: ""
}
}
*/
// Default result depends on current window.navigator.userAgent value


// Now let's try a custom user-agent string as an example
var uastring1 = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Ubuntu/11.10 Chromium/15.0.874.106 Chrome/15.0.874.106 Safari/535.2";
parser.setUA(uastring1);
var result = parser.getResult();
// You can also use UAParser constructor directly without having to create an instance:
// var result = UAParser(uastring1);


console.log(result.browser);        // {name: "Chromium", version: "15.0.874.106"}
console.log(result.device);         // {model: undefined, type: undefined, vendor: undefined}
console.log(result.os);             // {name: "Ubuntu", version: "11.10"}
console.log(result.os.version);     // "11.10"
console.log(result.engine.name);    // "WebKit"
console.log(result.cpu.architecture);   // "amd64"