如何让DeviceOrientationEvent和DeviceMotionEvent在Safari上运行?

Sie*_*els 7 javascript safari mobile-safari device-orientation devicemotion

我正在尝试在我的网站上实现DeviceOrientationEvent和DeviceMotionEvent以获得3D效果。但是,该控制台不会记录任何信息,并且显然iOS 13需要用户设置权限才能开始执行此操作。我似乎无法弄清楚如何正确设置它。

我已经做了一些研究,这就是我发现的东西:https : //github.com/w3c/deviceorientation/issues/57#issuecomment-498417027

可悲的是,在线提供的所有其他方法不再可用。

window.addEventListener('deviceorientation', function(event) {
    console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
});
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

[警告]在请求并授予许可之前,不会触发任何设备运动或定向事件。

小智 9

if ( location.protocol != "https:" ) {
location.href = "https:" + window.location.href.substring( window.location.protocol.length );
}
function permission () {
    if ( typeof( DeviceMotionEvent ) !== "undefined" && typeof( DeviceMotionEvent.requestPermission ) === "function" ) {
        // (optional) Do something before API request prompt.
        DeviceMotionEvent.requestPermission()
            .then( response => {
            // (optional) Do something after API prompt dismissed.
            if ( response == "granted" ) {
                window.addEventListener( "devicemotion", (e) => {
                    // do something for 'e' here.
                })
            }
        })
            .catch( console.error )
    } else {
        alert( "DeviceMotionEvent is not defined" );
    }
}
const btn = document.getElementById( "request" );
btn.addEventListener( "click", permission );
Run Code Online (Sandbox Code Playgroud)

使用页面上的元素作为事件触发器并为其指定“请求”ID。

这将检查 https 并在请求 API 授权之前根据需要进行更改。昨天找到这个,但不记得网址。

  • 这会在 iPhone 6S (iOS 12) 上的 Safari 浏览器中发出“DeviceMotionEvent 未定义”警报。为什么不起作用? (4认同)

小智 7

从iOS 13 beta 2开始,您需要调用DeviceOrientationEvent.requestPermission()来访问陀螺仪或加速度计。这将显示一个权限对话框,提示用户允许该站点的运动和方向访问。

请注意,如果您尝试在页面加载时自动调用它,则此方法将无效。用户需要采取一些措施(例如点击按钮)才能显示对话框。

另外,当前的实现似乎要求该站点启用https。

有关更多信息,请参阅此页面


Pax*_*nus 7

您需要单击或用户手势来调用 requestPermission()。像这样 :

<script type="text/javascript">
    function requestOrientationPermission(){
        DeviceOrientationEvent.requestPermission()
        .then(response => {
            if (response == 'granted') {
                window.addEventListener('deviceorientation', (e) => {
                    // do something with e
                })
            }
        })
        .catch(console.error)
    }
</script>

<button onclick='requestOrientationPermission();'>Request orientation permission</button>
Run Code Online (Sandbox Code Playgroud)

注意:如果您在权限提示上单击“取消”并想再次测试它,则需要退出 Safari 并重新启动它才能再次出现提示。