I have an Android app with a WebView which loads multiple URLs with links. Some of these URLs are opened in a Chrome Browser (or Chrome Custom Tabs) and these loaded pages write to localStorage using window.localStorage.putItem("someKey", "someValue")
.
When I try to access those values from my WebView by doing a window.localStorage.getItem("someKey")
the returned result is null.
Conversely, if I write a value to localStore in my WebView and then try to read it from Browser I see the null value again.
My WebView has javaScript and domStorage enabled:
class HelloWebViewClient extends WebViewClient {
public Context mContext;
public HelloWebViewClient(Context mContext) {
this.mContext = mContext;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
launchCCT(url);
return true;
}
private void launchCCT(String url) {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
Bundle headers = new Bundle();
customTabsIntent.intent.putExtra(Browser.EXTRA_HEADERS, headers);
customTabsIntent.launchUrl(MainActivity.this, Uri.parse(url));
}
}
WebView myWebView = (WebView) findViewById(R.id.myWebView);
myWebView.setWebViewClient(new HelloWebViewClient(this));
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setDatabaseEnabled(true);
myWebView.loadUrl(<url goes here>);
Also the Target API in manifest.xml is 31 running on Android 11.
My WebView displays the following HTML:
<!DOCTYPE html>
<html>
<head>
<script>
function chromeCustomTabOpen()
var Window;
Window = window.open(
"https://myserver/setLocalStorageValue");
}
function readFromLocalStorage() {
alert("Some value is: " + window.localStorage.getItem("someKey"))
}
</script>
</head>
<body>
<button onclick="chromeCustomTabOpen()">
Open Custom Tab
</button>
<button onclick="readFromLocalStorage()">
Read from local storage
</button>
</body>
</html>
First I click the Open Custom Tab
button which loads the following HTML page:
<!DOCTYPE html>
<html>
<head>
</head>
<body onpageshow="onpageshowMethod()">
<h1>Set Local Storage Value</h1>
<script type="text/javascript">
function onpageshowMethod(event) {
window.localStorage.setItem("someKey", "someValue");
}
</script>
</body>
</html>
Then I close the CCT and when I am back to the WebView I click on Read from local storage
button which results in null
value shown in alert.
How do I force Android to share localStorage values across Browser (or CCT) and WebViews?