evaluateJavascript(String script, ValueCallback<String> resultCallback) method is added to WebView on Android in SDK 19.
Android documentation quotes:
If non-null, resultCallback will be invoked with any result returned from that execution.
I am using this method as shown below, but somehow my callback is not being invoked. I can see from debugging that the evaluateJavascript() is called, but the call back is not being invoked in Android API 19, 20 & 21. From API 22 (LOLLIPOP_MR1) onwards, everything is working as expected.
Calling webview.loadURL("") before evaluateJavascript() makes it work on all the API levels. I want to understand why and would appreciate if somebody can shed some light / share any links about this. If I can understand why, I want to see if calling loadURL() could be avoided. There is another unrelated problem which makes loadURL() a non-preferable solution.
Code:
private void webViewTest() {
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
Log.d("TEST", "BEFORE"); // LOGGED
// webview.loadUrl(""); // Enabling this makes it work on all Android versions
webview.evaluateJavascript("(function(){return 'test'})()", new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
Log.d("TEST", "From JS: " + s); // NEVER LOGGED on API 19-21
}
});
Log.e("TEST", "AFTER"); // LOGGED
}
runOnUiThread(new Runnable() {
@Override
public void run() {
webViewTest();
}
});
Please find an example of this problem at https://github.com/bashok001/TestApp
loadData()orloadDataWithBaseURL()can't be used instead.load...()methods, it is breaking another functionality. So, I want to understand why callingload...()makes it all work in 19, 20, 21.