android 的webkit的api的开放程度还是非常不错,java可以和webview内的javascript很好的交互。下面的小例子可以说明这一点。
先看我们的html文档:
<html> <script language="javascript"> /* This function is invoked by the activity */ function wave() { alert("1"); document.getElementById("droid").src="android_waving.png"; alert("2"); } </script> <body> <!-- Calls into the javascript interface for the activity --> <a onClick="window.demo.clickOnAndroid()"><div style="width:80px;margin:0px auto;padding:10px;text-align:center;border:2px solid #202020;" > <img id="droid" src="android_normal.png"/><br> Click me! </div></a> </body> </html>
再看我们的java 代码。
public class WebViewDemo extends Activity { private static final String LOG_TAG = "WebViewDemo"; private WebView mWebView; private Handler mHandler = new Handler(); @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = mWebView.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); mWebView.setWebChromeClient(new MyWebChromeClient()); mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo"); mWebView.loadUrl("file:///android_asset/demo.html"); } final class DemoJavaScriptInterface { DemoJavaScriptInterface() { } /** * This is not called on the UI thread. Post a runnable to invoke * loadUrl on the UI thread. */ public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { mWebView.loadUrl("javascript:wave()"); } }); } } /** * Provides a hook for calling "alert" from javascript. Useful for * debugging your javascript. */ final class MyWebChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d(LOG_TAG, message); result.confirm(); return true; } } }
WebView 的addJavascriptInterface函数就可以实现彼此的交互。