通過列印控制檯訊息或通過遠端除錯來排除 WebView 故障
將 webview 控制檯訊息列印到 logcat
要從網頁處理 console
訊息,你可以覆蓋 WebChromeClient
中的 onConsoleMessage
:
final class ChromeClient extends WebChromeClient {
@Override
public boolean onConsoleMessage(ConsoleMessage msg) {
Log.d(
"WebView",
String.format("%s %s:%d", msg.message(), msg.lineNumber(), msg.sourceId())
);
return true;
}
}
並將其設定在你的活動或片段中:
webView.setWebChromeClient(new ChromeClient());
所以此示例頁面:
<html>
<head>
<script type="text/javascript">
console.log('test message');
</script>
</head>
<body>
</body>
</html>
將日誌’測試訊息’寫入 logcat:
WebView:測試訊息 sample.html:4
chrome-client 也支援 console.info()
,console.warn()
和 console.error()
。
使用 Chrome 遠端除錯 Android 裝置
你可以從桌面 Chrome 遠端除錯基於 webview 的應用程式。
在 Android 裝置上啟用 USB 除錯
在 Android 裝置上,開啟設定,找到開發人員選項部分,然後啟用 USB 除錯。
連線並發現你的 Android 裝置
在 Chrome 頁面中開啟頁面: chrome:// inspect /#devices
在檢查裝置對話方塊中,選擇你的裝置並按檢查。Chrome 的 DevTools 的新例項在你的開發機器上開啟。
有關 DevTools 的更詳細指南和說明,請訪問 developers.google.com