14

Before I load a URL on WebView i want to set a value inside browser LocalStorage.

Till now the only way I did managed to set this value is after the page is loaded. This is how I can set the value:

browser.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
                loadUrl("javascript: LocalStorage.set('namespace', 'key', 'value');");
        }
}

I did try to override the method onPageStarted(), but the value is not stored.

How can I set this key/value before the call browser.loadUrl()? The url/page depends on this value, so I need to set the value before I load the page.

Bugdr0id
  • 2,962
  • 6
  • 35
  • 59
  • why not using SharedPreferences (for example), if you want to store things...? – OWADVL Oct 27 '15 at 16:22
  • 2
    I need to save data inside Webview, so Webpage javascript can read it. I don't see how SharedPreferences can solve my problem. – Bugdr0id Nov 02 '15 at 09:08

2 Answers2

7

What you can do is set a redirect into the javascript to the actual url and load the javascript plus redirect using webview.loadData().

 String injection = "<html><head><script type='javascript'>LocalStorage.set('namespace', 'key', 'value');window.location.replace('YOUR_URL_HERE');</script></head><body></body></html>";
 webview.loadData(injection, "text/html", null); 

Be aware though that you might need to save that to a file first before it works: see How to load a javascript redirect into android webview?

Community
  • 1
  • 1
Niki van Stein
  • 10,564
  • 3
  • 29
  • 62
2

You can use WebViewClient.onPageStarted() for this.

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        String js = "window.localStorage.setItem('key', 'value');";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(js, null);
        } else {
            webView.loadUrl("javascript:" + js);
        }
    }
});
david.krasznai
  • 101
  • 2
  • 3