创建一个测试html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebView Error Test</title>
<script>
// 强制触发一个错误
function triggerError() {
console.error("This is a test error message");
throw new Error("This is a thrown JavaScript error");
}
</script>
</head>
<body>
<h1>WebView Error Log Test</h1>
<button onclick="triggerError()">Trigger Error</button>
</body>
</html>
webView加载
webView.loadUrl("file:///android_asset/error_test.html");
使用onConsoleMessage捕获javascript异常
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.e("WebView-JS", "Line: " + consoleMessage.lineNumber()
+ " Source: " + consoleMessage.sourceId()
+ " Message: " + consoleMessage.message());
return true; // 返回 true 表示消息已被处理
}
});
在 WebView 中开启WebView 调试模式
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
在chrome浏览器中输入
chrome://inspect
在手机中进入H5页面
能看到打开的h5页面,例如文中的 WebView Error Test 点击 inspect fallback
点击 trigger Error 按钮 就可以看到右侧的报错内容