Search code examples
javascriptaccelerometergyroscope

How to access accelerometer/gyroscope data from Javascript?


I have recently come across a few websites that seems to access the accelerometer or gyroscope on my laptop, detecting changes in orientation or movement.

How is this done? Must I subscribe to some kind of event on the window object?

On which devices (laptops, mobile phones, tablets) is this known to work?


NB: I actually already know (part of) the answer to this question, and I am going to post it right away. The reason that I am posting the question here, is to let everyone else know that accelerometer data is available in Javascript (on certain devices) and to challenge the community to post new findings on the subject. Currently, there seems to be almost no documentation of these features.


Solution

  • 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
    }