DeviceOrientationEvent 不适用于所有服务器

DeviceOrientationEvent not working on all servers

我在计算机的虚拟机上安装了 fedora,并且我一直在尝试让 deviceOrientation 事件在我 phone.

上查看站点时触发

它没有工作,所以使用这个线程的答案:How to check for a device/browser that fully supports the deviceorientation event?,我 运行 这个代码来检查它是否被支持:

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

这导致 "nope"。但我知道我的 phone 支持 deviceOrientation,因为 MDN 上的示例有效。

然后,我将 完全相同的 文件上传到我自己的网站,你瞧,它给了我 "haz!".

我不知道为什么我使用的服务器会影响是否支持 deviceOrientation。我唯一能想到的是它可能需要 SSL,但我在任何文档中都没有看到 SSL,而且我之前在 raspberry pi 上托管的网站上使用过 deviceOrientation,但没有SSL.

从 v.76 开始 Chrome 要求您所在的页面是通过 https 提供的。

这可以通过转到此 http:// fiddle which will output nope, while the same fiddle served through https:// 看到,将输出 haz!,就像下面的代码片段一样,它是通过 https:

提供的

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

Here is the chromium bug 引入了此限制。

请注意,如果它只是为了您自己的目的,那么您可以通过使用 --unsafely-treat-insecure-origin-as-secure, apparently it's also possible to do it on mobile versions 启动您的 Chrome 来利用它(虽然我没有测试自己)。