使用JS检测MacOS,iOS,Windows,Android和Linux OS

Vla*_*rak 8 javascript operating-system

如何使用JavaScript检测MacOS X,iOS,Windows,Android和Linux操作系统?

Vla*_*rak 66

我学到了很多关于window.navigator对象及其属性:platform,appVersionuserAgent.在我看来,几乎不可能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)

灵感:

  1. 到今天为止navigator.platform的可能值列表是什么?
  2. 使用JavaScript或jQuery检测Mac OS X或Windows计算机的最佳方法
  3. 如何使用JavaScript检测我的浏览器版本和操作系统?
  4. 如何使用javaScript检测浏览器和操作系统名称和版本

我还使用移动和桌面浏览器列表来测试我的代码:

  1. 所有移动浏览器列表
  2. 所有浏览器列表

此代码正常工作.我在所有操作系统上测试过它:MacOS,iOS,Android,Windows和UNIX,但我无法保证100%确定.

  • 既然“navigator.platform”已被弃用,是不是该更新一下了?https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/platform (4认同)
  • 为什么不直接在 MacOS 上使用“Mac”?应该是更多的未来证明。 (3认同)
  • 您应该将“darwin”添加到“macosPlatforms” (3认同)
  • `iosPlatforms.indexOf(platform) !== -1` 可以更明确地写为 `iosPlatforms.includes(platform)`。看起来您也可以使用字符串匹配来代替更通用的`platform.toLowerCase.startsWith("win")`。您还可以通过在每个 if 条件中使用 return 来消除变异变量(`return 'Windows'`)。 (3认同)
  • 你为什么说“我写过这样的东西”?我想知道您使用的实际代码是什么以及为什么它与此处的代码不同。 (2认同)