一、问题简介
经测试,苹果手机ios13.3.1系统版本将影响到重力感应类H5的体验,特别是跟重力感应功能相关的效果:包括摇一摇触发,重力感应控制图片移动,layer 容器重力感应部分、一镜到底、全景容器组件中需要重力感应控制的部分、陀螺仪组件。
二、详细说明
苹果手机微信打开H5,主要借助苹果自带的Safari浏览器。最新苹果手机系统版本,限制了Safari浏览器获取用户感应器信息,只有经过用户同意才可获取,即没有经过H5打开用户的同意,H5没有权限使用重力感应功能。
三、解决方案
原本的解决方案失效,苹果加强了重力感应权限部分的控制,必须让用户通过点击元素的方式来获取当前用户重力感应权限授权。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body onload="init()">
<button id="btn">点击授权</button>
<script type="text/javascript">
document.getElementById("btn").addEventListener("click", function() {
if (typeof DeviceMotionEvent.requestPermission === 'function') {
DeviceMotionEvent.requestPermission()
.then(permissionState => {
if (permissionState === 'granted') {
window.addEventListener('devicemotion', deviceMotionHandler, false);
}
})
.catch((err) => {
alert("用户未允许权限");
});
} else {
alert("not found")
}
})
var SHAKE_THRESHOLD = 3000;
var last_update = 0;
var x = y = z = last_x = last_y = last_z = 0;
function init() {
if (window.DeviceMotionEvent) {
if (typeof DeviceMotionEvent.requestPermission === 'function') {
DeviceMotionEvent.requestPermission()
.then(permissionState => {
if (permissionState === 'granted') {
window.addEventListener('devicemotion', deviceMotionHandler, false);
}
})
.catch((err) => {
alert("用户未允许权限");
});
} else {
window.addEventListener('devicemotion', deviceMotionHandler, false);
}
} else {
alert('not support mobile event');
}
}
function deviceMotionHandler(eventData) {
var acceleration = eventData.accelerationIncludingGravity;
var curTime = new Date().getTime();
if ((curTime - last_update) > 100) {
var diffTime = curTime - last_update;
last_update = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
alert("摇动了");
}
last_x = x;
last_y = y;
last_z = z;
}
}
</script>
</body>
</html>