Javascript 使用 JS 检测 MacOS、iOS、Windows、Android 和 Linux 操作系统
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38241480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect MacOS, iOS, Windows, Android and Linux OS with JS
提问by Vladyslav Turak
How to detect MacOS X, iOS, Windows, Android and Linux operating system with JavaScript?
如何使用 JavaScript 检测 MacOS X、iOS、Windows、Android 和 Linux 操作系统?
回答by Vladyslav Turak
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.
我学到了很多关于window.navigator
对象及其属性的知识:platform
,appVersion
和userAgent
。在我看来,几乎不可能 100% 确定地检测到用户的操作系统,但在我的情况下,85%-90% 对我来说已经足够了。
So, after examining tons of the stackoverflows' answers and some articles, I've wrote something like this:
因此,在检查了大量 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());
Inspiration:
灵感:
- What is the list of possible values for navigator.platform as of today?
- Best way to detect Mac OS X or Windows computers with JavaScript or jQuery
- How to detect my browser version and operating system using JavaScript?
- How to detect Browser and Operating System Name and Version using javaScript
- 截至今天,navigator.platform 的可能值列表是什么?
- 使用 JavaScript 或 jQuery 检测 Mac OS X 或 Windows 计算机的最佳方法
- 如何使用 JavaScript 检测我的浏览器版本和操作系统?
- 如何使用 javaScript 检测浏览器和操作系统名称和版本
Also I used the lists of mobile and desktop browsers to test my code:
我还使用移动和桌面浏览器列表来测试我的代码:
This code works properly. I tested it on all the OS: MacOS, iOS, Android, Windows and UNIX, but I can't guarantee 100% sure.
此代码正常工作。我在所有操作系统上测试过它:MacOS、iOS、Android、Windows 和 UNIX,但我不能保证 100% 肯定。