【问题标题】:Detect the OS type with JS regardless of the devices [duplicate]无论设备如何,都使用 JS 检测操作系统类型 [重复]
【发布时间】:2021-11-11 11:01:12
【问题描述】:

使用 JavaScript 检测 MacOS、iOS、Windows、Android 和 Linux 操作系统的最佳方法是什么?

无论设备如何,答案都应返回操作系统的类型。 例如iOS 在 iPhone、iPad 上使用,并且答案应返回 iOS 作为 OS 类型。

寻找不使用 navigator.platform 属性的答案,因为它已被弃用。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    navigator.platform 已弃用,不应使用。以下方法基于检查 navigator.userAgent 属性。

    注意: navigator.userAgent 可以被用户或浏览器扩展伪造,因此不能保证以下功能 100% 工作。

    以下代码是从here 派生和修改的。无法在该线程上发布答案,因此在此处分享。

    function getPlatformOS() {
      const userAgent = window.navigator.userAgent;
      let os = null;
    
      const isIOS = (/iPad|iPhone|iPod/.test(userAgent) ||
      (/Mac|Mac OS|MacIntel/gi.test(userAgent) && (navigator.maxTouchPoints > 1 || "ontouchend" in document))) && !window.MSStream;
    
      if (/Macintosh|Mac|Mac OS|MacIntel|MacPPC|Mac68K/gi.test(userAgent)) {
        os = 'Mac OS';
      } else if (isIOS) {
        os = 'iOS';
      } else if (/'Win32|Win64|Windows|Windows NT|WinCE/gi.test(userAgent)) {
        os = 'Windows';
      } else if (/Android/gi.test(userAgent)) {
        os = 'Android';
      } else if (/Linux/gi.test(userAgent)) {
        os = 'Linux';
      }
    
      return os;
    }
    console.log(getPlatformOS())

    检测iOS是基于here的一些答案

    【讨论】:

    • “无法在该线程上发布答案,因此在此处分享”- 该问题已关闭是有原因的。你应该注意那个原因,而不是重复同样的错误。
    • @Quentin 我知道它很接近,但如果我想发布最新的答案,那我该怎么做?
    • 想想为什么它被关闭了。
    • 我知道这是其他问题的重复,但我的解决方案是独立的,不包括任何已弃用的方法。
    • 所以因为你对同一个问题的回答不同,你认为你不应该回答已经问过的问题,而是应该重复那个问题,然后回答你自己的重复问题?这没有意义。
    猜你喜欢
    • 2014-09-17
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多