【发布时间】:2021-11-11 11:01:12
【问题描述】:
使用 JavaScript 检测 MacOS、iOS、Windows、Android 和 Linux 操作系统的最佳方法是什么?
无论设备如何,答案都应返回操作系统的类型。 例如iOS 在 iPhone、iPad 上使用,并且答案应返回 iOS 作为 OS 类型。
寻找不使用 navigator.platform 属性的答案,因为它已被弃用。
【问题讨论】:
标签: javascript
使用 JavaScript 检测 MacOS、iOS、Windows、Android 和 Linux 操作系统的最佳方法是什么?
无论设备如何,答案都应返回操作系统的类型。 例如iOS 在 iPhone、iPad 上使用,并且答案应返回 iOS 作为 OS 类型。
寻找不使用 navigator.platform 属性的答案,因为它已被弃用。
【问题讨论】:
标签: javascript
navigator.platform 已弃用,不应使用。以下方法基于检查 navigator.userAgent 属性。
注意: navigator.userAgent 可以被用户或浏览器扩展伪造,因此不能保证以下功能 100% 工作。
以下代码是从here 派生和修改的。无法在该线程上发布答案,因此在此处分享。
function getPlatformOS() {
const userAgent = window.navigator.userAgent;
let os = null;
const isIOS = (/iPad|iPhone|iPod/.test(userAgent) ||
(/Mac|Mac OS|MacIntel/gi.test(userAgent) && (navigator.maxTouchPoints > 1 || "ontouchend" in document))) && !window.MSStream;
if (/Macintosh|Mac|Mac OS|MacIntel|MacPPC|Mac68K/gi.test(userAgent)) {
os = 'Mac OS';
} else if (isIOS) {
os = 'iOS';
} else if (/'Win32|Win64|Windows|Windows NT|WinCE/gi.test(userAgent)) {
os = 'Windows';
} else if (/Android/gi.test(userAgent)) {
os = 'Android';
} else if (/Linux/gi.test(userAgent)) {
os = 'Linux';
}
return os;
}
console.log(getPlatformOS())
检测iOS是基于here的一些答案
【讨论】: