How to Detect Phone Movement with a PWA (Accelerometer)

In the last two posts I covered what a PWA is and how to make a button that vibrates your phone. This time: reading your phone's motion sensor — the same one phone games use to tilt a ball or steer a car.
window.addEventListener("devicemotion", (event) => {
const { x, y, z } = event.acceleration;
console.log(x, y, z);
});
x: left / right tilt
y: forward / back tilt
z: up / down movement
iPhone needs one extra step
On Android/Chrome this works right away. On iPhone/Safari, the browser requires a permission prompt triggered by a tap:
async function enableMotion() {
if (typeof DeviceMotionEvent.requestPermission === "function") {
const result = await DeviceMotionEvent.requestPermission();
if (result !== "granted") return;
}
window.addEventListener("devicemotion", onMotion);
}
Always call requestPermission() from a button's click handler — calling it automatically on page load gets blocked.
A simple shake detector
A common use for this sensor: detect when the phone is shaken.
let lastX, lastY, lastZ, lastTime = 0;
const THRESHOLD = 15; // higher = needs a harder shake
function onMotion(event) {
const { x, y, z } = event.acceleration;
const now = Date.now();
if (now - lastTime < 100) return; // check 10x per second
if (lastX !== undefined) {
const delta = Math.abs(x - lastX) + Math.abs(y - lastY) + Math.abs(z - lastZ);
if (delta > THRESHOLD) {
navigator.vibrate?.(100);
console.log("Shake detected!");
}
}
lastX = x; lastY = y; lastZ = z;
lastTime = now;
}
Combine this with the vibration code from the last post and you get instant feedback: shake the phone, feel a buzz.
What you need to know
Needs HTTPS, same as every sensor API.
iPhone needs a tap to grant permission; Android doesn't.
Works in the browser, no app store involved — same PWA approach as the rest of this series.
Good uses: shake-to-refresh, step counters, tilt-controlled games, spirit levels.
What's next
Project 3 in this series: camera and flashlight access from a PWA.