如何在Safari上让DeviceOrientationEvent和DeviceMotionEvent正常工作?

14

我正在尝试在我的网站上实现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);
});

我收到了以下错误信息:

[警告] 在请求和获得权限之前,不会触发任何设备运动或方向事件。

5个回答

21
截至iOS 13 beta 2,您需要调用DeviceOrientationEvent.requestPermission()才能访问陀螺仪或加速度计。这将呈现一个权限对话框,提示用户允许该站点访问运动和方向。
请注意,如果您尝试在页面加载时自动调用它,这将不起作用。用户需要采取一些操作(如点击按钮)才能显示对话框。
此外,当前的实现似乎要求网站启用https。
有关更多信息,请参见此页面

14
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 );

使用页面上的一个元素作为事件触发器,并将其ID设置为"request"。

这将检查https并在请求API授权之前如有必要更改它。昨天发现了这个,但不记得URL。


4
这在我的 iPhone 6S(iOS 12)的 Safari 浏览器中提示“DeviceMotionEvent 未定义”。 为什么它不能工作? - FireFuro99

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>

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

0

这不是一个真正的答案,但如果在WKWebView上使用DeviceMotion,需要考虑一些事情。

在Xcode 13中,您可以使用这个新的WKUIDelegate。您仍然需要像其他答案中提到的那样请求权限,但它不会提示用户授权,而是直接授予。

@available(iOS 15, *)
func webView(_ webView: WKWebView,
    requestDeviceOrientationAndMotionPermissionFor origin: WKSecurityOrigin,
         initiatedByFrame frame: WKFrameInfo,
          decisionHandler: @escaping (WKPermissionDecision) -> Void) {
    decisionHandler(.grant)
}

0
在 Xamarin iOS (Xamarin.Forms) 上,您可以使用 WkWebView 的 EvaluateJavaScript 方法,在其准备就绪时注入权限请求脚本:
webView.EvaluateJavaScript("DeviceMotionEvent.requestPermission().then(response => { if (response == 'granted') {window.addEventListener('devicemotion', (e) => {})}}).catch(console.error)");

如果使用自定义的WkWebView渲染器(如果这个bug仍然存在,必须实现IWKUIDelegate https://bugs.webkit.org/show_bug.cgi?id=203287),则可以在设置webView控件时注入脚本OnElementChanged 例如:
// do this when setting up the webview control in OnElementChanged
                //enable device motion sensors permission script:
                //https://medium.com/flawless-app-stories/how-to-request-device-motion-and-orientation-permission-in-ios-13-74fc9d6cd140
                var source =
                "function requestSensorPermission() {" +
                "   if (typeof(DeviceMotionEvent) !== 'undefined' && typeof(DeviceMotionEvent.requestPermission) === 'function') {" +
                "       DeviceMotionEvent.requestPermission() .then(response => {" +
                "           if (response == 'granted') { " +
                "               window.addEventListener('devicemotion', (e) => { })" +
                "           }" +
                "       }).catch(console.error)" +
                "   }" +
                "}";
                var script = new WKUserScript(new NSString(source), WKUserScriptInjectionTime.AtDocumentEnd, true);
                wkWebView.Configuration.UserContentController.AddUserScript(script);

yourCustomWebView准备好后,您可以在代码后台中调用yourCustomWebView.EvaluateJavaScript("requestSensorPermission()")。

EvaluateJavaScript:https://learn.microsoft.com/en-us/dotnet/api/webkit.wkwebview.evaluatejavascript?view=xamarin-ios-sdk-12

自定义WkWebView渲染器:https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview#create-the-custom-renderer-on-ios


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接