javaandroidcallbackandroid-webviewandroid-webview-javascript

Android Webview EvaluateJavascript sometimes does not return a response


I have been trying to fix this for weeks and have no clue what is causing the issue. In my project I am utilizing the Android Webview's evaluateJavascript() method like this:

    this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            webView.evaluateJavascript(command, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //Parsing and taking action here
                    Log.d("Response", value);
                }
            });
        }
    });

A sample string of the javascript I am sending would be:

document.getElementById("message").value="Stuff worked!"; 

or

document.getElementById("some-awesome-button").click(); 

While 9 times out of 10 these calls return a value in the onReceiveValue() method, once in a while I just straight never receive a response at all.

This lack of a response has made chaining events a nightmare and I have no clue why this would be happening.

Some more data to head off any additional questions:

    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAllowFileAccess(true);

It almost seems like the issue is with the Javascript Bridge but I cannot be certain.

The summary question I have is, what could cause the Android WebView's evaluateJavascript() call to not trigger a callback nor return a value in the onReceiveValue() method?


Solution

  • I did eventually figure out what happened here.

    The shorter version is, this can happen when you have a memory leak and an object that is utilizing a semi-destroyed webview will fire off commands, but the newly-initialized webview will not receive a response because it is going to a dead listener.

    If you want to prevent this from occurring, just make sure that all objects that maintain an application Context are properly disposed of or correctly reset if the activity restarts, else you have all objects that use the same Application-level context, but are using new views and callbacks entirely.