Android如何将值写入HTML5 localstorage?

Wat*_*lla 14 javascript html5 android local-storage android-webview

我有一个webview android应用程序,它打开一个包含一些HTML5/JavaScript代码的网页.我想将一些值从我的应用程序的android端传递到浏览器端.所以我想从Android写入HTML5 localstorage,然后网页的Javascript部分读取localstorage中的值.

Android webview如何写入HTML5 localstorage?

或者是否有一种方式Android可以将一些值传递给它加载的页面的javascript?(无需重新加载整个页面)说在HTML5 localstorage上写一些内容然后javascript代码从HTML5 localstorage中读取该内容

它与如何将json格式的数据从webview传递到html页面不同.我需要一种通过android写入HTML5 localstorage的方法

Ale*_*lin 19

传递变量,如字符串stackoverflow post:

   webView.getSettings().setJavaScriptEnabled(true);
   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 +"');");
               }
            }
   });
Run Code Online (Sandbox Code Playgroud)

第二个变体是使用JavaScriptInterface

初始部分

 JavaScriptInterface jsInterface = new JavaScriptInterface(this);
 webView.getSettings().setJavaScriptEnabled(true);
 webView.addJavascriptInterface(jsInterface, "JSInterface");
Run Code Online (Sandbox Code Playgroud)

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 == "give me data" && this.activity.data) {
                return this.activity.data;
           }else{
                return null;
           }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Js部分

<script>
  function ready() {
        var data = window.JSInterface.getData("give me data");
        localStorage.put("give me data", data)
  };

  document.addEventListener("DOMContentLoaded", ready);
</script>
Run Code Online (Sandbox Code Playgroud)