我想知道是否有可能检测浏览器是否在iOS上运行,类似于使用Modernizer进行功能检测(尽管这显然是设备检测,而不是功能检测).
通常情况下,我会倾向于功能检测,但我需要找出设备是否是iOS,因为根据问题YouTube API not working with iPad / iPhone / non-Flash device,设备处理视频的方式
我想知道是否有可能检测浏览器是否在iOS上运行,类似于使用Modernizer进行功能检测(尽管这显然是设备检测,而不是功能检测).
通常情况下,我会倾向于功能检测,但我需要找出设备是否是iOS,因为根据问题YouTube API not working with iPad / iPhone / non-Flash device,设备处理视频的方式
iOS 13 iPad both User agent and platform strings are changed和differentiating between iPad and MacOS seems possible,所以下面的所有答案现在都需要考虑到这一点.
这可能是也涵盖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
将是true
或false
用户代理嗅探比较危险,问题也经常出现.
On iPad iOS 13, the user agent is identical with that of a MacOS 13 computer,但如果你忽略iPad,这可能会持续一段时间:
var iOS = !window.MSStream && /iPad|iPhone|iPod/.test(navigator.userAgent); // fails on iPad iOS 13
!window.MSStream
是为了不错误地检测IE11,参见here和here.
Note:用户或浏览器扩展都可以伪造navigator.userAgent
和navigator.platform
.
存在用于更改用户代理或平台的浏览器扩展,是因为网站使用了过于繁重的检测,并且经常禁用某些功能,即使用户的浏览器本来可以使用该功能.
为了减少与用户的冲突,建议针对每个 case 专门检测您的网站所需的确切功能.然后,当用户获得具有所需功能的浏览器时,它将在不需要额外代码更改的情况下工作.
检测IOS版本的最常用方法是通过parsing it from the User Agent string检测.但也有feature detection inference*;
我们知道history API
是在iOS4-matchMedia API
年,iOS5-webAudio API
年,iOS6-WebSpeech API
年,iOS7年等等.
Note:以下代码不可靠,如果这些HTML5功能中的任何一个在较新的iOS版本中被弃用,这些代码将被 destruct .你被警告了!
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';
}