我无法以相同的代码在Chrome,Firefox,IE11和Edge上使用其他一些答案。我想出了以下内容,它似乎适用于上面列出的那些浏览器。我还想查看用户使用的操作系统。我尚未针对具有覆盖用户的用户代理设置的浏览器进行过测试,因此里程可能会有所不同。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));
}