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

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


当前回答

你也可以使用include

  const isApple = ['iPhone', 'iPad', 'iPod', 'iPad Simulator', 'iPhone Simulator', 'iPod Simulator',].includes(navigator.platform)

其他回答

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

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

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

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

在iOS 13 iPad中,用户代理和平台字符串都被改变了,iPad和MacOS之间的区别似乎是可能的,所以下面的所有回答都需要考虑到这一点。

这可能是覆盖iOS 13的最短替代方案:

function iOS() {
  return [
    'iPad Simulator',
    'iPhone Simulator',
    'iPod Simulator',
    'iPad',
    'iPhone',
    'iPod'
  ].includes(navigator.platform)
  // iPad on iOS 13 detection
  || (navigator.userAgent.includes("Mac") && "ontouchend" in document)
}

iOS要么为真,要么为假

更糟糕的选择:用户代理嗅探

用户代理嗅探更加危险,经常出现问题。

在iPad iOS 13上,用户代理与MacOS 13计算机上的用户代理相同,但如果你忽略iPad,这可能仍然可以工作一段时间:

var iOS = !window.MSStream && /iPad|iPhone|iPod/.test(navigator.userAgent); // fails on iPad iOS 13

!窗口。MSStream是为了不错误地检测IE11,请看这里和这里。

注意:都是导航器。userAgent和navigator。平台可以被用户或浏览器扩展伪造。

改变userAgent或平台的浏览器扩展存在,因为网站使用了过于繁重的检测,并且经常禁用一些功能,即使用户的浏览器本来可以使用这些功能。

为了减少与用户的冲突,建议针对每种情况专门检测您的网站需要的确切功能。然后,当用户得到一个具有所需功能的浏览器时,它就已经可以工作了,而无需额外的代码更改。

检测iOS版本

检测iOS版本的最常见方法是从User Agent字符串中解析它。但也有特征检测推断*;

我们知道,历史API是在iOS4中引入的,matchMedia API是在iOS5中引入的,webAudio API是在iOS6中引入的,WebSpeech API是在iOS7中引入的,等等。

注意:以下代码是不可靠的,如果这些HTML5功能中的任何一个在更新的iOS版本中被弃用,就会中断。我警告过你!

function iOSversion() {

  if (iOS) { // <-- Use the one here above
    if (window.indexedDB) { return 'iOS 8 and up'; }
    if (window.SpeechSynthesisUtterance) { return 'iOS 7'; }
    if (window.webkitAudioContext) { return 'iOS 6'; }
    if (window.matchMedia) { return 'iOS 5'; }
    if (window.history && 'pushState' in window.history) { return 'iOS 4'; }
    return 'iOS 3 or earlier';
  }

  return 'Not an iOS device';
}

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