'Xamarin forms android WebView - Sessions not working
I have a Xamarin forms project, which has a WebView, this displays an external website which is built in C# and uses Session storage.
The website within the WebView functions correctly on iOS, but on Android any Session data is not working, Cookie data is working though.
if I go to the android device's browser the website works correctly, so I assume its a setting on the WebView itself, I have tried a custom render and setting the DomStorageEnabled to true, but this has not resolved the issue.
Can anyone help??
Here is my custom render code
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
((HybridWebView)Element).Cleanup();
}
if (e.NewElement != null)
{
Android.Webkit.CookieManager.Instance.SetAcceptThirdPartyCookies(Control, true);
var test = Android.Webkit.CookieManager.Instance.AcceptCookie();
Android.Webkit.CookieManager.Instance.SetAcceptCookie(true);
Control.Settings.JavaScriptEnabled = true;
Control.Settings.DomStorageEnabled = true;
Control.Settings.SetAppCacheEnabled(true);
}
}
Solution 1:[1]
As i know, UWP and iOS would share their cookie containers automatically between the WebView and native http client, however Android does not.
The WebView could use CookieManager to handle cookies. If you want to share cookies between the two, you will have to manually process the information. You need to know the Uri of the domain for these cookies.
private void CopyCookies(HttpResponseMessage result, Uri uri)
{
foreach (var header in result.Headers)
if (header.Key.ToLower() == "set-cookie")
foreach (var value in header.Value)
_cookieManager.SetCookie($"{uri.Scheme}://{uri.Host}", value);
foreach (var cookie in GetAllCookies(_cookieContainer))
_cookieManager.SetCookie(cookie.Domain, cookie.ToString());
}
public void ReverseCopyCookies(Uri uri)
{
var cookie = _cookieManager.GetCookie($"{uri.Scheme}://{uri.Host}");
if (!string.IsNullOrEmpty(cookie))
_cookieContainer.SetCookies(new Uri($"{uri.Scheme}://{uri.Host}"), cookie);
}
Or you could try to flush the cookies everytime.
protected override void OnPause()
{
base.OnPause();
Android.Webkit.CookieManager.Instance.Flush();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wendy Zang - MSFT |
