【问题标题】:Are there any restrictions on the event 'onDeviceMotion' on iOS?iOS 上的“onDeviceMotion”事件是否有任何限制?
【发布时间】:2025-12-03 06:00:02
【问题描述】:

我在访问 iOS 上的 onDeviceMotion 事件时遇到问题。它适用于 Android。

我正在学习教程,代码在我的 iOS 设备上运行良好,但是当我复制/粘贴完全相同的代码并从我的 iOS 设备上的本地主机运行它时,不会触发 onDeviceMotion 事件。 相同的代码在我的 Android 设备上的 Chrome 和 Firefox 上运行得很好。所以不是代码问题,我认为这是 Apple 的限制。

我使用的是 iOS 12 并启用了 Safari 上的运动传感器。

对于 iOS 上的运动事件,我应该注意哪些限制?比如必要的https还是CORS?我的服务器是用 Node.JS 编写的。

下面是我说的代码。

window.addEventListener('devicemotion', onDeviceMotion, true);

function onDeviceMotion(event) {
    let x = event.accelerationIncludingGravity.x;
    let y = event.accelerationIncludingGravity.y;
    let z = event.accelerationIncludingGravity.z;
}

谢谢!

【问题讨论】:

    标签: javascript ios node.js iphone events


    【解决方案1】:

    问题在于 Safari 会限制某些事件,尤其是运动事件,不能通过 HTTP 在不安全的网站上运行。您必须设置并启用 HTTPS,然后才会触发事件。

    Node.JS

    const privateKey = fs.readFileSync( 'keys/server.key' );
    const certificate = fs.readFileSync( 'keys/server.crt' );
    https.createServer({
        key: privateKey,
        cert: certificate
    }, app).listen(8080);
    

    【讨论】:

      最近更新 更多