android webview url显示'javascript',android - WebView's loadUrl("javascript:...") not working - Stack ...

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()");

}

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值