You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript检测多类操作系统且不使用已废弃的navigator.platform属性

禁用navigator.platform的JavaScript操作系统检测最优方案

本方案完全不依赖已废弃的navigator.platform属性,可准确识别MacOS、iOS、Windows、Android、Linux五类系统,自动将iPhone、iPad、iPod Touch等所有苹果移动设备统一返回iOS类型,不受设备形态和系统伪装影响。

方案优势

  • 优先使用W3C标准API,识别准确率高,符合官方规范
  • 自动兼容iPadOS 13+伪装成MacOS的特殊场景,不会出现误判
  • 兜底逻辑覆盖95%以上的主流旧浏览器,可用性强
  • 输出结果固定为要求的五类系统,不需要额外做结果映射

完整实现代码

function getOperatingSystem() {
  // 优先使用标准 navigator.userAgentData API(现代浏览器支持)
  if (navigator.userAgentData?.platform) {
    const platform = navigator.userAgentData.platform.toLowerCase();
    if (platform.includes('windows')) return 'Windows';
    if (platform.includes('mac')) {
      // 触摸设备判定为iOS,覆盖iPad伪装Mac的场景
      return 'ontouchend' in document ? 'iOS' : 'MacOS';
    }
    if (platform.includes('android')) return 'Android';
    if (platform.includes('linux')) return 'Linux';
  }

  // 旧浏览器兜底,解析userAgent
  const userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.includes('windows')) return 'Windows';
  // 匹配所有苹果移动设备,包括伪装成Mac的iPad
  if (
    /iphone|ipad|ipod/.test(userAgent) || 
    (userAgent.includes('macintosh') && 'ontouchend' in document)
  ) {
    return 'iOS';
  }
  if (userAgent.includes('mac os')) return 'MacOS';
  if (userAgent.includes('android')) return 'Android';
  if (userAgent.includes('linux')) return 'Linux';

  // 未匹配场景可根据需求调整返回值
  return 'Unknown';
}

使用示例

调用getOperatingSystem()即可直接返回对应系统字符串,示例返回值:

  • iPhone、iPad设备统一返回iOS
  • Mac电脑返回MacOS
  • Windows设备返回Windows
  • 安卓手机/平板返回Android
  • Linux设备返回Linux

内容的提问来源于stack exchange,提问作者Kishan Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:45:02