本来是想研究下WebView和JavaScript的代码互相调用的。
结果最后发现当html页面载入之后,即便是JavaScript的代码调用自己的方法也不能调用。
我试了试html文件在w3school上是可以正常执行的,就是按钮点击之后出现相应的对话框什么的。
但是同样的html文件被WebView载入之后,虽然按钮也显示,但是按下去后没有任何效果。
我的JavaScript使能属性也命名设置为true了啊。
JS代码:
sample0.html
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
alert("Hello World!");
}
function onAlert() {
alert("This is a alert sample from html");
}
function onConfirm() {
var b = confirm("are you sure to login?");
alert("your choice is " + b);
}
function onPrompt() {
var b = prompt("please input your password", "aaa");
alert("your input is " + b);
}
</script>
</head>
<body>
<button onclick="myFunction()">点击这里</button>
<input type="button" value="alert" onclick="onAlert()" />
<input type="button" value="confirm" onclick="onConfirm()" />
<input type="button" value="prompt" onclick="onPrompt()" />
</body>
</html>
Android代码:
Android代码
public class WebJSActivity extends Activity { private WebView myWebView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_js); myWebView = (WebView) findViewById(R.id.myWebView); // 得到设置属性的对象 WebSettings webSettings = myWebView.getSettings(); // 使能JavaScript webSettings.setJavaScriptEnabled(true); //限制在WebView中打开网页,而不用默认浏览器 //myWebView.setWebViewClient(new WebViewClient()); //载入页面:本地html资源文件 myWebView.loadUrl("file:///android_asset/sample0.html"); //绑定桥梁类和WebView中运行的JavaScript代码 //将一个对象起一个别名传入,在JS代码中用这个别名代替这个对象 myWebView.addJavascriptInterface(new WebAppInterface(this), "myInterfaceName"); }
好吧。。。Google果然还是比百度靠得住。。。
这个问题已经在这里被提出并且解决了:http://code.google.com/p/android/issues/detail?id=752
就是该链接#12回复的代码加上就可以了:
设置chrome handler并且覆写onJsAlert()方法:
myWebView.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { // TODO Auto-generated method stub return super.onJsAlert(view, url, message, result); } });