简体   繁体   中英

How do you access the motion sensors (accelerometer, gyroscope) in a mobile browser webapp in/after 2019? Why does it no longer work?

I have code that is intended to measure device motion on a mobile device, and it used to work in mobile browsers, but no longer does. Here's an example taken directly from the Mozilla web docs:

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);

As far as I can tell, code like this no longer works in a mobile browser (circa Aug 2019).

Why? What needs to be done?

After spending time trying to debug my own code, I discovered that the many examples/demos/testers available on the web also no longer work, eg:

http://www.gianpa.com/shake/

http://www.albertosarullo.com/demos/accelerometer/

It seems that this is related to some changes in modern browsers/permissions/etc, perhaps related to recently revealed security issues related to accelerometer access, and steps being taken by Apple and Google as a result, eg:

https://www.macrumors.com/2019/02/04/ios-12-2-safari-motion-orientation-access-toggle/

What I found is that neither a recent Android phone running up to date Chrome nor a relatively recent iOS phone running Safari seem to allow webapp access to the motion sensors anymore. However, when I load the same demo code (eg from the above demo websites) on an older Android device... it works fine as it used to.

What needs to be done to access motion data within a webapp?

Thank you

Apparently it is now required to serve and access a website/webapp using https:// for it to be able to use the motion sensors. I accessed the same URL above that didn't provide any sensor data using http://, and it did work using https://

If you have an older version of Chrome 63, please enable the chrome://flags/#enable-generic-sensor flag.

If you are using environmental sensors, such as, Magnetometer or AmbientLightSensor, please also enable chrome://flags/#enable-generic-sensor-extra-classes flag.

Reference: https://intel.github.io/generic-sensor-demos/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM