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

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


当前回答

如果您正在使用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');
}

其他回答

如果你正在使用React,有一个很棒的库可以解决这类问题:React - agent。(使用ua-parser-js构建。)

https://github.com/medipass/react-ugent

可用的浏览器有:

Chrome, chromium, edge, firefox,即,lynx, safari, opera

可用的操作系统包括:

安卓,黑莓,铬操作系统,debian, ios, linux, MAC操作系统,ubuntu, unix, Windows

可选设备包括:

游戏机、电脑、手机、平板电脑、智能电视、可穿戴、嵌入式

易于使用:

<Ugent browser="safari" os="ios">
  <div>
    This text only shows on Safari on iOS.
  </div>
</Ugent>

如果你不使用React,你可以使用- ua-parser-js

https://github.com/faisalman/ua-parser-js

在我的案例中,用户代理不够好,因为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
}

检测iOS(均<12和13+)

社区维基,因为编辑队列说它是满的,所有其他答案目前是过时或不完整的。

const iOS_1to12 = /iPad|iPhone|iPod/.test(navigator.platform);

const iOS13_iPad = (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1));

const iOS1to12quirk = function() {
  var audio = new Audio(); // temporary Audio object
  audio.volume = 0.5; // has no effect on iOS <= 12
  return audio.volume === 1;
};

const isIOS = !window.MSStream && (iOS_1to12 || iOS13_iPad || iOS1to12quirk());

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

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

iOS设备上的用户代理会显示iPhone或iPad。我只是根据这些关键词进行筛选。