如何使用新的navigator.userAgentData检测iPad或平板设备?
原检测代码
const iPad = !!(navigator.userAgent.match(/(iPad)/) || (navigator.platform === "MacIntel" && typeof navigator.standalone !== "undefined")); const userAgent = navigator.userAgent.toLowerCase(); const isTablet = /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/.test(userAgent);
控制台警告
Audit usage of navigator.userAgent, navigator.appVersion, and navigator.platform
A page or script is accessing at least one of navigator.userAgent, navigator.appVersion, and navigator.platform. Starting in Chrome 101, the amount of information available in the User Agent string will be reduced.
To fix this issue, replace the usage of navigator.userAgent, navigator.appVersion, and navigator.platform with feature detection, progressive enhancement, or migrate to navigator.userAgentData.
Note that for performance reasons, only the first access to one of the properties is shown.
navigator.userAgentData可用属性
navigator.userAgentData.brands → Array navigator.userAgentData.mobile → true/false navigator.userAgentData.platform → e.g. "macOS" or "Windows"
问题
如何修改上述代码,以实现iPad或平板设备的检测?
核心思路
优先使用navigator.userAgentData获取设备信息,针对iPadOS的特殊识别逻辑做适配,同时保留降级方案兼容不支持userAgentData的旧浏览器。
修改后的代码
function isTabletOriPad() { // 优先使用标准的userAgentData API if ('userAgentData' in navigator) { const { platform, mobile } = navigator.userAgentData; // 识别Android平板、Windows平板:非移动设备+对应平台 if (!mobile && (platform.includes('Android') || platform.includes('Windows'))) { return true; } // 识别iPadOS:平台为macOS + 支持standalone(iPadOS特有PWA特性) + 触摸设备 if (platform === 'macOS' && typeof navigator.standalone !== 'undefined' && 'ontouchstart' in window) { return true; } // 其余情况排除平板 return false; } // 降级方案:兼容不支持userAgentData的浏览器 const userAgent = navigator.userAgent.toLowerCase(); const isTablet = /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/.test(userAgent); const isiPad = !!(navigator.userAgent.match(/(iPad)/) || (navigator.platform === 'MacIntel' && typeof navigator.standalone !== 'undefined')); return isTablet || isiPad; } // 使用示例 const isTabletDevice = isTabletOriPad();
关键说明
- iPadOS适配:iPadOS会伪装成macOS,
userAgentData.mobile返回false,因此通过navigator.standalone(仅iOS/iPadOS支持的PWA属性)和触摸能力来确认是iPad - 其他平板识别:Android/Windows平板的
userAgentData.mobile为false,且平台标识明确,可直接判定 - 降级兼容:旧浏览器保留原有User Agent检测逻辑,但需注意未来浏览器可能进一步限制该字段的信息
内容的提问来源于stack exchange,提问作者Avatar

