我正在寻找一种使用Javascript来获取客户端操作系统的通用方法。许多记录在案的解决方案都使用用户代理,而我在堆栈溢出时也遇到过时的类似问题/解答。下面提供了一个示例函数,但是我想知道是否有更全面的版本可以满足以下准则:
- 所有现代且广泛使用的OS应该具有一个版本,例如,而不是仅是 Windows ,而应具有 Windows 10 或 Windows 7
- 较旧且很大程度上冗余的OS可以组合在一起,例如 Windows 98 , Windows Vista 可能只是 Windows
- 在可能的版本中还需要包含移动操作系统,例如 Android 7.0
- 代码不应太长,目的是要区分当前最流行的系统。
下面的示例在没有太多思考的情况下被放在一起,我正在寻找一个更好的版本
function getOS() {
var osStr;
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("windows xp") !== -1) {
osStr = "WindowsXP";
} else if (ua.indexOf("windows nt 6.1") !== -1) {
osStr = "Windows7";
} else if (ua.indexOf("windows nt 10.0") !== -1) {
osStr = "Windows10";
} else if (ua.indexOf("iemobile") !== -1 || ua.indexOf("windows phone") !== -1) {
osStr = "WindowsMobile";
} else if (ua.indexOf("windows") !== -1) {
osStr = "Windows";
} else if (ua.indexOf("ipad") !== -1) {
osStr = "ipad";
} else if (ua.indexOf("ipod") !== -1) {
osStr = "iTouch)";
} else if (ua.indexOf("iphone") !== -1) {
osStr = "iPhone)";
} else if (ua.indexOf("cros") !== -1) {
osStr = "ChromeOS";
} else if (ua.indexOf("android") !== -1) {
osStr = "Android";
} else if (ua.indexOf("blackberry") !== -1) {
osStr = "Blackberry";
} else if (ua.indexOf("palm") !== -1) {
osStr = "PalmOS";
} else if (ua.indexOf("kindle") !== -1) {
osStr = "Kindle";
} else if (ua.indexOf("ubuntu") !== -1) {
osStr = "Ubuntu";
} else if (ua.indexOf("linux") !== -1) {
osStr = "Linux";
} else if (ua.indexOf("nix") !== -1) {
osStr = "UNIX";
} else {
osStr = "Unknown";
}
return osStr;
}