【发布时间】:2016-11-09 12:52:36
【问题描述】:
如何使用 JavaScript 检测 MacOS X、iOS、Windows、Android 和 Linux 操作系统?
【问题讨论】:
标签: javascript operating-system
如何使用 JavaScript 检测 MacOS X、iOS、Windows、Android 和 Linux 操作系统?
【问题讨论】:
标签: javascript operating-system
我学到了很多关于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());
灵感:
我还使用了移动和桌面浏览器列表来测试我的代码:
此代码可以正常工作。我在所有操作系统上进行了测试:MacOS、iOS、Android、Windows 和 UNIX,但我不能保证 100% 确定。
【讨论】:
"darwin"添加到macosPlatforms
!os && 开头?