Search code examples
javascriptserverdevice-orientation

DeviceOrientationEvent not working on all servers


I have fedora installed on a virtual machine on my computer, and I've been trying to get deviceOrientation events to fire when I view the site on my phone.

It hasn't been working, so using the answer from this thread: How to check for a device/browser that fully supports the deviceorientation event?, I ran this code to check if it's supported:

if (window.DeviceOrientationEvent && 'ontouchstart' in window) {
    // setup real compass thing, with event.alpha
    document.write("haz!");
} else {
    // setup some mouse following hack
    document.write("nope");
}

This results in "nope". But I know that my phone supports deviceOrientation, because the example on MDN works.

Then, I uploaded the exact same file to my own website, where lo and behold, it gave me "haz!".

I have no idea why the server I use should make a difference to whether deviceOrientation is supported. The only thing I can think of is that maybe it requires SSL, but I don't see SSL mentioned anywhere in any documentation, and I have previously used deviceOrientation on a website hosted on my raspberry pi, which didn't have SSL.


Solution

  • From v.76 Chrome requires that the page you are on is served through https.

    This can be seen by going to this http:// fiddle which will output nope, while the same fiddle served through https:// will output haz!, just like the snippet below, which is served through https:

    if (window.DeviceOrientationEvent) {
        console.log("haz!");
    } else {
        console.log("nope");
    }

    Here is the chromium bug that introduced this restriction.

    Note that if it is only for your own purpose, then you can leverage it by starting your Chrome with the --unsafely-treat-insecure-origin-as-secure, apparently it's also possible to do it on mobile versions (though I didn't test myself).