Java调用JavaScript
webView.loadUrl(“javascript:fn()”);
其中fn方法是H5页面中的JavaScript函数。
JavaScript调用Java
需要三个步骤:
1. 调用与WebView关联的WebSetting实例的setJavaScriptEnabled方法启用功能。
2. 调用WebView的addJavascriptInterface将应用中的Java对象暴露给JavaScript。
3. 在JavaScript脚本中调用Java对象的方法。
要加载的Html页面部分代码:
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
暴露的Java对象定义:
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
在WebView中绑定对象:
WebView webView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
但是在Andriod4.2之前的系统上存在严重的安全隐患,引起WebView远程代码执行漏洞。Andriod4.2开始官方进行了修复,需要对暴露给JavaScript调用的方法加上 @JavascriptInterface注解。那么在Andriod4.2以前的系统上如何规避这个安全隐患呢?那就是不要再使用addJavascriptInterface这种方式,转而使用其他途径。