I am playing with Android's WebView: I have a sample text "asdf" which shall be dyed when the user clicks on a button (red, green or blue). To make things a little bit more complicated, the WebView first tells the Java code to trigger the color change and then from within Java the WebView is changed:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
final WebAppInterface webAppInterface = new WebAppInterface(this, myWebView);
myWebView.addJavascriptInterface(webAppInterface, "Android");
myWebView.loadUrl("file:///android_asset/index.html");
}
}
This is the interface:
public class WebAppInterface {
Context context;
WebView webView;
WebAppInterface(Context context, WebView webView) {
this.context = context;
this.webView = webView;
}
@JavascriptInterface
public void dye(String color) {
switch (color) {
case "red":
webView.loadUrl("javascript:dyeRed()");
break;
case "green":
webView.loadUrl("javascript:dyeGreen()");
break;
case "blue":
webView.loadUrl("javascript:dyeBlue()");
break;
}
}
}
In my html file there are 3 buttons like this one:
RED
And inside a javascript file that gets successfully loaded I have functions like these:
function callDyeRed() {
Android.dye("red");
}
function dyeRed() {
document.getElementsByTagName('body')[0].style.color = 'red';
}
When I click on the button I see that inside WebAppInterface the line webView.loadUrl("javascript:dyeRed()") is executed. Thus, the js->Java communication works. However, the opposite is not true: Javascript code is not executed afterwards.
What am I missing here?
If I change the color from within a WebViewClient, the communication works:
myWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView webView, String url) {
webView.loadUrl("javascript:dyeGreen()");
}
});