[英]How to get the Javascript messages from android webview
Hey guys I wanted to inject some code into a webview and see whether the code has succeeded. 大家好,我想在Webview中注入一些代码,看看代码是否成功。 I've tried to override the onConsoleMessage method of WebChromeClient but it only reports whether the code is an uncaught reference
我尝试覆盖WebChromeClient的onConsoleMessage方法,但它仅报告代码是否为未捕获的引用
public boolean onConsoleMessage (ConsoleMessage consoleMessage){
System.out.println(consoleMessage.message());
}
I only get messages like: 我只收到以下消息:
Uncaught ReferenceError: noob is not defined
When I execute a valid command like 当我执行有效的命令时
document.getElementById("mainPage").innerHTML = "Hello Dolly.";
I would want to somehow know that the command succeeded or failed. 我想以某种方式知道命令成功还是失败。 The content of mainPage div changed fine but I got no messages from the onConsole method whether the command finished with success or not.
mainPage div的内容变化很好,但是无论命令是否成功完成,onConsole方法都没有消息。 Any idea what I could do?
知道我能做什么吗? Thanks in advance
提前致谢
That method is a callback, it does not do what you want. 该方法是一个回调,它不会执行您想要的操作。
Try this 尝试这个
webView.loadUrl("javascript:alert('Hey there!')");
to inject javascript. 注入JavaScript。
Then you set up a custom WebViewClient to the WebView and override onReceivedError to detect any JS errors. 然后,将自定义WebViewClient设置为WebView并重写onReceivedError以检测任何JS错误。
Theres also this method evaluateJavascript which might be useful to inject JS and detect if it succeeded. 也Theres这种方法evaluateJavascript这可能是有用的JS注入和检测,如果它成功了。 Your script string would look like this:
您的脚本字符串如下所示:
(function() {
try {
//do something
return "ok";
} catch(err){
return "error";
}
})();
So you would call it like this: 因此,您可以这样称呼它:
mWebView.evaluateJavascript(<above script here>, new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
if("ok".equals(s)){
} else {
//error
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.