如何使用 JavaScript 检测 MacOS X、iOS、Windows、Android 和 Linux 操作系统?
使用 JS 检测 MacOS、iOS、Windows、Android 和 Linux 操作系统
IT技术
javascript
operating-system
2021-03-06 13:20:28
1个回答
我学到了很多关于window.navigator
对象及其属性的知识:platform
,appVersion
和userAgent
。在我看来,几乎不可能 100% 确定地检测到用户的操作系统,但在我的情况下,85%-90% 对我来说已经足够了。
因此,在检查了大量 stackoverflows 的答案和一些文章之后,我写了这样的内容:
function getOS() {
var userAgent = window.navigator.userAgent,
platform = window.navigator.platform,
macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
iosPlatforms = ['iPhone', 'iPad', 'iPod'],
os = null;
if (macosPlatforms.indexOf(platform) !== -1) {
os = 'Mac OS';
} else if (iosPlatforms.indexOf(platform) !== -1) {
os = 'iOS';
} else if (windowsPlatforms.indexOf(platform) !== -1) {
os = 'Windows';
} else if (/Android/.test(userAgent)) {
os = 'Android';
} else if (!os && /Linux/.test(platform)) {
os = 'Linux';
}
return os;
}
alert(getOS());
灵感:
- 截至今天,navigator.platform 的可能值列表是什么?
- 使用 JavaScript 或 jQuery 检测 Mac OS X 或 Windows 计算机的最佳方法
- 如何使用 JavaScript 检测我的浏览器版本和操作系统?
- 如何使用 javaScript 检测浏览器和操作系统名称和版本
我还使用移动和桌面浏览器列表来测试我的代码:
此代码正常工作。我在所有操作系统上测试过它:MacOS、iOS、Android、Windows 和 UNIX,但我不能保证 100% 肯定。