现在的 APP,Android 与 H5 混合开发已很常见。当 Android 通过 WebView 加载 H5 页面,且需要向其传参时,可以用 loaclstorage 来实现。代码如下:
WebView 先要设置如下属性:
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCacheMaxSize(1024*1024*8);
String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
webView.getSettings().setAppCachePath(appCachePath);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAppCacheEnabled(true);
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
然后,传递参数:
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
String key = "hello";
String val = "world";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("localStorage.setItem('"+ key +"','"+ val +"');", null);
} else {
webView.loadUrl("javascript:localStorage.setItem('"+ key +"','"+ val +"');");
}
}
});
JavaScriptInterface 部分的代码如下:
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
public string getData(String someParameter){
//also you can return json data as string and at client side do JSON.parse
if (someParameter == "transmitData" && this.activity.data) {
return this.activity.data;
}else{
return null;
}
}
}
Js 部分的代码如下:
<script>
function ready() {
var data = window.JSInterface.getData("transmitData");
localStorage.put("transmitData", data)
};
document.addEventListener("DOMContentLoaded", ready);
</script>