在 Xamarin iOS (Xamarin.Forms) 上,您可以在 WkWebView 准备好时使用 WkWebView 上的方法注入权限请求脚本EvaluateJavaScript
:
webView.EvaluateJavaScript("DeviceMotionEvent.requestPermission().then(response => { if (response == 'granted') {window.addEventListener('devicemotion', (e) => {})}}).catch(console.error)");
如果使用自定义 WkWebView 渲染器(如果此错误仍然存在,则必须实现 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()") 。
评估JavaScript:
https ://docs.microsoft.com/en-us/dotnet/api/webkit.wkwebview.evaluatejavascript?view=xamarin-ios-sdk-12
自定义 WkWebView 渲染器: https ://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview#create-the-custom-renderer-on-ios