H5检测手机摇一摇要实现h5检测手机摇一摇动作可以直接调用h5原生api。但是在我的实践中发现在ios中限制条件比较多,
一. 简介
要实现h5检测手机摇一摇动作可以直接调用h5原生api。但是在我的实践中发现在ios
中限制条件比较多,体验还是有些区别的。
二. 如何监听
调用Window: devicemotion event
即可实现监听。devicemotion
事件以固定的时间间隔触发,并指示设备当时在接收的加速物理力量。 它还提供有关旋转速率的信息(如果有)。
function handleMotionEvent(event) {
var x = event.accelerationIncludingGravity.x;
var y = event.accelerationIncludingGravity.y;
var z = event.accelerationIncludingGravity.z;
// Do something awesome.
}
window.addEventListener("devicemotion", handleMotionEvent, true);
三. 安卓机
安卓机上直接按照如上即可实现。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试摇一摇</title>
</head>
<body>
<div class="phone">
<div id="show">摇一摇</div>
</div>
</body>
<script>
function handleMotionEvent(event) {
document.getElementById('show').innerHTML = '摇动中'
}
if (window.DeviceMotionEvent) {
window.addEventListener("devicemotion", handleMotionEvent, false);
} else {
alert("该浏览器不支持摇一摇功能");
}
</script>
</html>
四. iPhone
1. 限制
在ios
上限制有两条:
- h5必须是
https
协议的 - 必须用户点击授权才可以调用
devicemotion
2. 授权
function getPermission() {
if (
typeof window.DeviceMotionEvent !== 'undefined' &&
typeof window.DeviceMotionEvent.requestPermission === 'function'
) {
window.DeviceMotionEvent.requestPermission()
.then(function(state) {
if ('granted' === state) {
//用户同意授权
} else {
//用户拒绝授权
alert('摇一摇需要授权设备运动权限,请重启应用后,再次进行授权!')
}
})
.catch(function(err) {
alert('error: ' + err)
})
}
}
直接调用该函数请求授权会导致报错:
error: NotAllowedError: Requesting device orientation or motion access requires a user gesture to prompt
需要用户主动去请求授权,因此此处需要将调用放到比如一个按钮上,让用户去点击请求授权。
<button onclick="getPermission()">请求授权</button>
3. 全部代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试摇一摇</title>
</head>
<body>
<div class="phone">
<button onclick="getPermission()">请求授权</button>
<div id="show"></div>
</div>
</body>
<script>
function handleMotionEvent(event) {
document.getElementById('show').innerHTML = '摇动中'
}
function startListen() {
if (window.DeviceMotionEvent) {
window.addEventListener("devicemotion", handleMotionEvent, false);
} else {
alert("该浏览器不支持摇一摇功能");
}
}
function getPermission() {
if (
typeof window.DeviceMotionEvent !== 'undefined' &&
typeof window.DeviceMotionEvent.requestPermission === 'function'
) {
window.DeviceMotionEvent.requestPermission()
.then(function(state) {
if ('granted' === state) {
//用户同意授权
startListen()
} else {
//用户拒绝授权
alert('摇一摇需要授权设备运动权限,请重启应用后,再次进行授权!')
}
})
.catch(function(err) {
alert('error: ' + err)
})
}
}
</script>
</html>
五. 原文链接
转载自:https://juejin.cn/post/6956381943399186463