Android - save value on LocalStorage before WebView.loadUrl()
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);
}
}
});
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?