問題描述
如何使用 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:
- 所有移動瀏覽器列表
- 所有瀏覽器列表
此代碼可以正常工作.我在所有操作系統上進行了測試: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操作系統的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!