Vla*_*rak 8 javascript operating-system
如何使用JavaScript检测MacOS X,iOS,Windows,Android和Linux操作系统?
Vla*_*rak 66
我学到了很多关于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());Run Code Online (Sandbox Code Playgroud)
灵感:
我还使用移动和桌面浏览器列表来测试我的代码:
此代码正常工作.我在所有操作系统上测试过它:MacOS,iOS,Android,Windows和UNIX,但我无法保证100%确定.
| 归档时间: |
|
| 查看次数: |
27418 次 |
| 最近记录: |