The way to do this in 2019+ is to use DeviceOrientation
API. This works in most modern browsers on desktop and mobile.
window.addEventListener("deviceorientation", handleOrientation, true);
After registering your event listener (in this case, a JavaScript function called handleOrientation()), your listener function periodically gets called with updated orientation data.
The orientation event contains four values:
DeviceOrientationEvent.absolute
DeviceOrientationEvent.alpha
DeviceOrientationEvent.beta
DeviceOrientationEvent.gamma
The event handler function can look something like this:
function handleOrientation(event) { var absolute = event.absolute; var alpha = event.alpha; var beta = event.beta; var gamma = event.gamma; // Do stuff with the new orientation data }