Android WebView使用Javascript详解
public class WebViewDemo extends Activity {private WebView mWebView;private Handler mHandler = new Handler();public void onCreate(Bundle icicle) {super.onCreate(icicle);setContentView(R.layout.webviewdemo);mWebView = (WebView) findViewById(R.id.webview);WebSettings webSettings = mWebView.getSettings();webSettings.setJavaScriptEnabled(true);mWebView.addJavascriptInterface(new Object() {public void clickOnAndroid() {mHandler.post(new Runnable() {public void run() {mWebView.loadUrl("javascript:wave()");}});}}, "demo");mWebView.loadUrl("file:///android_asset/demo.html");}}
?这里的重点是addJavascriptInterface(Object obj,String interfaceName)方法,该方法将一个java对象绑定到一个javascript对象中,javascript对象名就是interfaceName,作用域是Global。这样初始化webview后,在webview加载的页面中就可以直接通过javascript:window.demo访问到绑定的java对象了。来看看在html中是怎样调用的:
………………………………
?
阅读全文>>