我正在寻找一种获取客户端操作系统的Javascript通用方法。许多记录在案的解决方案都使用用户代理,而我在堆栈溢出时也遇到过时的类似问题/解答。下面提供了一个示例函数,但我想知道是否有更全面的版本可以满足以下准则:
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;
}
但是,您可以使用一些API,这些API已经为您完成了艰苦的工作https://developers.whatismybrowser.com/api/features/user-agent-parse是一个很棒的工具,它将为您解析用户代理字符串
这里是更全面的列表,其中包含每个示例https://www.whatsmyua.info/
function getPlatform() {
var uap = UAParser(navigator.userAgent);
var osVersion = uap.os.version;
if (osVersion == null) {
osVersion = "";
}
var browserVersion = uap.browser.major;
if (browserVersion == null) {
browserVersion = "";
}
var platform = uap.os.name + osVersion + "_" + uap.browser.name + browserVersion;
platform = platform.replace(/\s/g, '');
return platform;
}
被调用时返回无空格字符串
OS_UA,该字符串作为URL的一部分从客户端转发到服务器。