How can Android write a value onto HTML5 localstorage? How can Android write a value onto HTML5 localstorage? android android

How can Android write a value onto HTML5 localstorage?


Pass variables like a string 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 +"');");               }            }   });

The second variant is to use JavaScriptInterface

Init section

 JavaScriptInterface jsInterface = new JavaScriptInterface(this); webView.getSettings().setJavaScriptEnabled(true); webView.addJavascriptInterface(jsInterface, "JSInterface");

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;           }        }    }

Js section

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


How can Android webview write onto the HTML5 localstorage?

   localStorage.setItem("data", value);

Note: With local storage, web applications can store data locally within the user's browser. HTML local storage; better than cookies.
Try addJavaScriptInterface() to bind your android class and webpage.


You can do it by Location Hash Property of javascript..

Android Code may look like this

WebView myWebView = (WebView) findViewById(R.id.myWebView);  myWebView.loadUrl("http://www.example.com/#any_value");myWebView.setWebViewClient(new MyWebViewClient());

And Javascript code look like this

var x = location.hash; //this will access the hash value you pass in urllocalStorage.setItem("save_my_value", x);