如何使用javascript检测iPad Pro是否为iPad?



我们能够像这样使用javascript检测iPad设备:

function isDeviceiPad(){
return navigator.platform.match(/iPad/i);
}

这在检测iPad设备方面非常有效,但是当我们从iPad Pro (10.5 inch)检查时,它不会检测到它是iPad。

为了进一步调查,我们向下钻取到navigator对象,检查了platformuserAgent,并得到了以下结果:

navigator.platform = 'MacIntel';
navigator.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) 
AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Safari/605.1.15)';

问题是返回navigator.platform = 'MacIntel'(与MacBook Pro相同(而不是iPad。我们需要一种方法来检测这是iPad而不是MacBook Pro,但是导航器似乎不会像旧iPad那样返回iPad

知道我们如何解决这个问题吗?

iPadPro将浏览器navigator.platform报告为"MacIntel",但这与其他平台相同。

目前(2019年(iPadPro与其他平台之间的区别在于iPadPro支持触摸。

这里有几个有用的方法。

function isIOS() {
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
return true;
} else {
return navigator.maxTouchPoints &&
navigator.maxTouchPoints > 2 &&
/MacIntel/.test(navigator.platform);
}
}
function isIpadOS() {
return navigator.maxTouchPoints &&
navigator.maxTouchPoints > 2 &&
/MacIntel/.test(navigator.platform);
}

我猜iPad Pro已经升级到iPadOS 13 Beta。由于苹果声称在iPadOS上使用Safari进行桌面级浏览,因此移动Safari似乎也模仿了macOS的行为和用户代理。

所以,简短的回答是这是不可能的

但是,您可以从此问题的答案中尝试解决方法。

目前,在 2020 年 10 月,我知道的唯一方法是:

(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 0) || navigator.platform === 'iPad'

您可以使用正则表达式来实现此目的。

var isIPadPro = /Macintosh/.test(navigator.userAgent) && 'ontouchend' in document;

您可以使用屏幕尺寸来检查它,iPad pro带有2个不同的侧面。 详细实现波纹管,根据您的用例进行修改

function isIpadPro() {
var ratio = window.devicePixelRatio || 1;
var screen = {
width : window.screen.width * ratio,
height : window.screen.height * ratio
};
return (screen.width === 2048 && screen.height === 2732) || (screen.width === 2732 && screen.height === 2048) || (screen.width === 1536 && screen.height === 2048) || (screen.width === 2048 && screen.height === 1536);
}

屏幕尺寸参考:http://screensiz.es/

检测"iPad Pro 10.5"设备的最简单方法是检查其屏幕尺寸是否"window.screen.height x window.screen.width = 1112 x 834"

但是,我想知道为什么您需要检测设备型号。如果您想检测移动浏览器,请查看以下问题: 检测移动浏览器

您应该能够使用屏幕尺寸来区分它们。以为您需要找到要检测的每个iPad Pro的真正价值。

window.screen.height
window.screen.width

电容器有一个有用的网络插件来获取设备信息(https://capacitor.ionicframework.com/docs/apis/device#example(。 它不区分iPad Pro和普通iPad,但是您可以将此插件的使用与建议的屏幕尺寸解决方案结合使用。

如果你想自己做这件事,你可以看看这里的代码:https://github.com/ionic-team/capacitor/blob/master/core/src/web/device.ts

这是可能的。

您可以使用此功能。 这也将检查带有触摸设备(iPad 13(的Mac。

<script type="text/javascript">
if(iOS()){
alert('iOS');
}
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)
}
</script>

最新更新