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

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


当前回答

为了检测iOS版本,我们必须像这样用Javascript代码解构用户代理:

 var res = navigator.userAgent.match(/; CPU.*OS (\d_\d)/);
    if(res) {
        var strVer = res[res.length-1];
        strVer = strVer.replace("_", ".");
        version = strVer * 1;
    }

其他回答

如果您正在使用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中的用户代理与Mac OS中的用户代理相同,因此我不得不做一个讨厌的把戏:

var mql = window.matchMedia("(orientation: landscape)");

/**
 * If we are in landscape but the height is bigger than width
 */
if(mql.matches && window.screen.height > window.screen.width) {
    // IOS
} else {
    // Mac OS
}

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

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

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

更新:我最初的答案不包括在桌面模式下的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);

一个简化的、易于扩展的版本。

var iOS = ['iPad', 'iPhone', 'iPod'].indexOf(navigator.platform) >= 0;