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

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


当前回答

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

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

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

其他回答

为了检测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;
    }

我在几年前写过这个,但我相信它仍然有效:

if(navigator.vendor != null && navigator.vendor.match(/Apple Computer, Inc./) && navigator.userAgent.match(/iPhone/i) || (navigator.userAgent.match(/iPod/i))) 

    {

        alert("Ipod or Iphone");

    }

else if (navigator.vendor != null && navigator.vendor.match(/Apple Computer, Inc./) && navigator.userAgent.match(/iPad/i))  

    {

        alert("Ipad");

    }

else if (navigator.vendor != null && navigator.vendor.match(/Apple Computer, Inc./) && navigator.userAgent.indexOf('Safari') != -1)

    {

        alert("Safari");

    }

else if (navigator.vendor == null || navigator.vendor != null)

    {

        alert("Not Apple Based Browser");

    }

在iOS 13之后,你应该像这样检测iOS设备,因为iPad将不会被旧的方式检测为iOS设备(由于新的“桌面”选项,默认启用):

let isIOS = /iPad|iPhone|iPod/.test(navigator.platform)
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)

第一个条件适用于iOS < 13或禁用桌面模式的iPhone或iPad,第二个条件适用于默认配置的iPadOS 13,因为它将自己定位为Macintosh Intel,但实际上是唯一具有多点触摸的Macintosh。

与其说是一种破解,不如说是一种真正的解决方案,但对我来说很可靠

P.S.如前所述,你可能应该添加IE检查

let isIOS = (/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
!window.MSStream

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

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

这将变量_iOSDevice设置为true或false

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