我想知道是否有可能检测浏览器是否运行在iOS上,类似于你如何使用Modernizr进行功能检测(尽管这显然是设备检测而不是功能检测)。

通常情况下,我会倾向于功能检测,但我需要找出设备是否是iOS,因为他们处理视频的方式根据这个问题,YouTube API不适用于iPad / iPhone /非flash设备


当前回答

这将变量_iOSDevice设置为true或false

_iOSDevice = !!navigator.platform.match(/iPhone|iPod|iPad/);

其他回答

这将变量_iOSDevice设置为true或false

_iOSDevice = !!navigator.platform.match(/iPhone|iPod|iPad/);

如果您正在使用Modernizr,您可以为它添加一个自定义测试。

决定使用哪种检测模式并不重要(userAgent, navigator。Vendor或navigator.platform),您总是可以将其打包以便稍后使用。

//Add Modernizr test
Modernizr.addTest('isios', function() {
    return navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
});

//usage
if (Modernizr.isios) {
    //this adds ios class to body
    Modernizr.prefixed('ios');
} else {
    //this adds notios class to body
    Modernizr.prefixed('notios');
}

更新:我最初的答案不包括在桌面模式下的iPad(在即将推出的iPadOS 13及更高版本中,默认更改为桌面模式)。 这对我的用例很好,如果不适合你,使用这个更新:

// iPhone and iPad including iPadOS 13+ regardless of desktop mode settings

iOSiPadOS = /^iP/.test(navigator.platform) ||
           /^Mac/.test(navigator.platform) && navigator.maxTouchPoints > 4;

这应该是安全的,只要 台式mac电脑根本不支持触摸事件 或不超过4个触摸点(当前iOS设备支持5个触摸点) 这是因为regexp ^首先检查平台字符串的起始位置,如果没有“iP”就停止(无论如何都比搜索长UA字符串直到结束快)。 它比导航仪安全。userAgent检查为导航器。平台不太可能是伪造的 检测iPhone / iPad模拟器


ORIGINAL ANSWER:
Wow, a lot of longish tricky code here. Keep it simple, please!

以我之见,这一个速度快,省钱,而且运行良好:

 iOS = /^iP/.test(navigator.platform);

  // or, if you prefer it verbose:
 iOS = /^(iPhone|iPad|iPod)/.test(navigator.platform);

因为导航器。平台已弃用,最好不再使用,我想添加一个其他解决方案。

你可以通过检查navigator.vendor来过滤MacOS系统。 当结果是苹果电脑公司,你知道它是MacOS。

没有必要测试导航器。userAgent或navigator.platform:

const isIOS = typeof navigator.standalone === 'boolean';

导航器。standalone只在iOS Safari上设置。参见MDN, Safari HTML参考。