現在的 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>