我为 Android WebView 编写了一个 JS SDK,用于收集设备方向和运动。 SDK 监听窗口上的 deviceorientation
和 devicemotion
事件,如下所示:
window.addEventListener('devicemotion', (event) => {...})
window.addEventListener('deviceorientation', (event) => {...})
在某些设备/集成上,我没有获得传感器数据。我试图模仿一个“坏”的集成,试图通过将以下内容添加到应用程序 list 来阻止 WebView 传感器访问,但没有成功。 JS 事件仍然被触发:
<activity
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize"
除了一起禁用 JS 之外,还有什么其他可能的方法来阻止 WebView 触发事件?
更新:
一些见解:
问题最多的设备是:
- 三星 Galaxy Tab 10.1 SM-T580
- 三星 Galaxy J5 Prime SM-G570M
更新 2
我在某些设备上的 IOS 上也有类似的问题,最有问题的是:
- Mozilla/5.0(iPhone;CPU iPhone OS 12_3_1,如 Mac OS X) AppleWebKit/605.1.15(KHTML,如 Gecko)移动/15E148
最佳答案
可能是,不可能通过 android 停止仅触发 JS 事件,如果你想要它,那么它会禁用整个 JS。
//disabled
wView.getSettings().setJavaScriptEnabled(false);
//enabled
wView.getSettings().setJavaScriptEnabled(true);
正如您所说,在某些设备上您没有获取传感器数据,为此您需要检查您的 webview decleration 代码。 示例代码在这里:
wView= new WebView(this);
wView.getSettings().setLoadsImagesAutomatically(true);
wView.getSettings().setJavaScriptEnabled(true);
wView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wView.setWebViewClient(new WebViewClient() {
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(MainActivity.this, description, Toast.LENGTH_SHORT).show();
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
});
wView.loadUrl(HOST_URL);
在 list 中
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize" />
关于javascript - 在 Android WebView 上阻止 JS deviceorientation devicemotion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57026960/