Hey guys I wanted to inject some code into a webview and see whether the code has succeeded. I've tried to override the onConsoleMessage method of WebChromeClient but it only reports whether the code is an uncaught reference
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. 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.
Then you set up a custom WebViewClient to the WebView and override onReceivedError to detect any JS errors.
Theres also this method evaluateJavascript which might be useful to inject JS and detect if it succeeded. 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
}
}
});