【问题标题】:Detect MacOS, iOS, Windows, Android and Linux OS with JS [duplicate]使用 JS 检测 MacOS、iOS、Windows、Android 和 Linux OS [重复]
【发布时间】:2016-11-09 12:52:36
【问题描述】:

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

【问题讨论】:

    标签: javascript operating-system


    【解决方案1】:

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

    灵感:

    1. What is the list of possible values for navigator.platform as of today?
    2. Best way to detect Mac OS X or Windows computers with JavaScript or jQuery
    3. How to detect my browser version and operating system using JavaScript?
    4. How to detect Browser and Operating System Name and Version using javaScript

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

    1. List of all Mobile Browsers
    2. List of all Browsers

    此代码可以正常工作。我在所有操作系统上进行了测试:MacOS、iOS、Android、Windows 和 UNIX,但我不能保证 100% 确定。

    【讨论】:

    • 为什么不在 MacOS 上使用“Mac”?应该是更多的未来证明。
    • 你应该将"darwin"添加到macosPlatforms
    • 你为什么说“我写过这样的东西”?我想知道您使用的实际代码是什么,为什么它与这里的不同。
    • 为什么最后一个 elseif 以 !os && 开头?
    • 由于“navigator.platform”已被弃用,是不是该更新它了? developer.mozilla.org/en-US/docs/Web/API/NavigatorID/platform
    猜你喜欢
    • 2017-07-30
    • 2021-03-01
    • 2012-01-29
    • 1970-01-01
    • 2011-08-20
    • 2017-05-24
    • 2012-12-26
    • 2012-09-16
    • 2017-01-31
    相关资源
    最近更新 更多