先提下兩種方式
方式一:
//先載入html檔案,然後調用html檔案中的javascript函數
webView.loadUrl("file:///android_asset/show.html");
webView.loadUrl("javascript:pushNewsData('"+strHtml+"')");
方式二:
//在Java代碼中添加javascript的介面,然後在html檔案中調用java中的對象
webView.addJavascriptInterface(strHtml, "MyContent");
先讓瀏覽器支援javascript
webView.getSettings().setJavaScriptEnabled(true);//開啟就可以用js的功能
Js代碼,放在asset檔案夾下,也可以在伺服器端,這樣改變內容,只需改伺服器端,用戶端不用修改
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript">function btn_test() {/* 列印,logcat裡的tag是Web Console */console.log("btn_test");}function call_java() {/* js調用java代碼,需要介面 */Window.interface_test.showToastFromWeb("hello i am javascript!");}function test_alert() {/* 彈出對話方塊 */alert("hello i am javascript!");}function test_confirm() {/* 彈出帶確定和取消按鈕的對話方塊 */var v = confirm("hello i am javascript!");console.log("onfirm " + v);}function test_prompt() {/* 彈出帶輸入框的對話方塊 */var v = prompt("input you name!", "tom");console.log("prompt " + v);}</script></head><body><button onclick="btn_test()">test</button><button onclick="call_java()">call_java</button><button onclick="test_alert()">test_alert</button><button onclick="test_confirm()">test_confirm</button><button onclick="test_prompt()">test_prompt</button><label tel:800800284>tel:8008233</label></body></html>
Java代碼裡
對應call_java()方法
webView.addJavascriptInterface(new Object(){public void showToastFromWeb(String msg){showToast(msg);}}, "interface_test");
對應alert等方法
webView.setWebChromeClient(new WebChromeClient(){@Overridepublic void onProgressChanged(WebView view, int newProgress) {//這裡上一博文已提過}@Overridepublic boolean onJsAlert(WebView view, String url, String message,JsResult result) {// TODO Auto-generated method stubreturn super.onJsAlert(view, url, message, result);}@Overridepublic boolean onJsConfirm(WebView view, String url,String message, JsResult result) {// TODO Auto-generated method stubreturn super.onJsConfirm(view, url, message, result);}@Overridepublic boolean onJsPrompt(WebView view, String url, String message,String defaultValue, JsPromptResult result) {// TODO Auto-generated method stubreturn super.onJsPrompt(view, url, message, defaultValue, result);}});
載入html
//webView.loadUrl("javascript:btn_test()");webView.loadUrl("file:///android_asset/test.html");