问题描述
如何使用JavaScript检测MacOS X,iOS,Windows,Android和Linux操作系统?
How to detect MacOS X, iOS, Windows, Android and Linux operating system with JavaScript?
推荐答案
我了解了很多有关 window.navigator
对象及其属性的信息: platform
, appVersion
和 userAgent
.在我看来,几乎不可能100%确定地检测用户的操作系统,但对我而言,85%-90%对我来说就足够了.
I learnt a lot about window.navigator
object and its properties: platform
, appVersion
and userAgent
. To my mind, it's almost impossible to detect user's OS with 100% sure, but in my case 85%-90% was enough for me.
因此,在检查了成堆的stackoverflows的答案和一些文章之后,我写了这样的内容:
So, after examining tons of the stackoverflows' answers and some articles, I wrote something like this:
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的操作系统名称和版本
我还使用了移动和桌面浏览器列表来测试我的代码:
Also I used the lists of mobile and desktop browsers to test my code:
此代码正常工作.我已经在所有OS(MacOS,iOS,Android,Windows和UNIX)上对其进行了测试,但是我不能保证100%肯定.
This code works properly. I tested it on all the OS: MacOS, iOS, Android, Windows and UNIX, but I can't guarantee 100% sure.
这篇关于使用JS检测MacOS,iOS,Windows,Android和Linux OS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!