javascriptnode.jsandroid-sensors

Phone grants access to sensor but browser doesn't support type 'Gyroscope'?


So I'm making a web app using JavaScript and on my phone the Permissions API call I make says that I am "granted" access to my gyroscope, yet when I try to call new Gyroscope({frequency: 60}) I catch an error that says my browser doesn't support it. I am running my code through a nodejs setup using vite to serve my content.

navigator.permissions.query({ name: 'gyroscope' })
.then(result => {
    if(result.state === 'granted') { // <-- this returns true
            try {
                this.gyroscope = new Gyroscope({frequency: 60});
                this.gyroscope.addEventListener('reading', e => {
                    console.log(e);
                });
                this.gyroscope.start();   
            } catch(error) {
                // Handle construction errors.
                if (error.name === 'SecurityError') {
                    // See the note above about feature policy.
                    alert('Sensor construction was blocked by a feature policy.');
                } else if (error.name === 'ReferenceError') {
                    alert('Sensor is not supported by the User Agent.');
                } else {
                    alert(error);
                }
            }
    } else {
        alert('No gyroscope or denied, computer assumed, falling back to keyboard.');
        // fallback setup here
    }
});

The error that triggers is this one Sensor is not supported by the User Agent.

I decided to investigate further and I stumbled upon this respository full of sensor tests: https://intel.github.io/generic-sensor-demos/sensor-tester/build/bundled/accelerometer and when I ran those on my phone, I passed all the tests.

So what am I missing here about using the Sensor API? I tried to look at the code from the repository above but I cannot for the life of me figure out how they make it work, when I can't.


Solution

  • For anyone who runs into this issue in the future, the problem was that the Sensor API requires SSL to work for everything. So to solve my issue, I went ahead and used mkcert to make a valid key.pem and cert.pem file to use with my local webserver setup.

    This is also a way to make SSL work for any localhost web development setup where SSL is needed.