2

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

John Smith
  • 844
  • 8
  • 26
  • Giggled at `noob is not defined`. Have you tried connecting to it via Chrome? – sg.cc Jan 29 '16 at 23:22
  • `onConsoleMessage` will only work when you do something with the console such as `console.log`. You could place `console.log` *after* your statements to make sure it didn't crash or something. – Mike Cluck Jan 29 '16 at 23:23
  • there has to be something that indicates that javascript has succeeded any ideas? – John Smith Jan 29 '16 at 23:38
  • @JohnSmith There's not. When you consider the fact that, ideally, all of your code works then it would be incredibly expensive to check if it *didn't* work. You could wrap your code in a `try-catch` block though. `try { doSomething(); } catch(err) { console.log(err); }` – Mike Cluck Jan 29 '16 at 23:42

1 Answers1

4

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
        }
    }
});
Mister Smith
  • 27,417
  • 21
  • 110
  • 193