Xamarin.Forms: Clear cookies in WebViews
If you are authenticating through WebView, and acquire a token on successful login, you may have experienced that on re-login scenarios the authentication details is not requested again, because the browser is storing the previously logged in user. You may have to clear the browser’s cookies section to get rid of the useless previous user’s details.
Go ahead and create a dependency service, because we will write some platform specific code! 🙂
Xamarin.Forms code
Define an interface like this
public interface IDeviceSpecificService
{
void ClearCookies();
}
And use the code like this
DependencyService.Get<IDeviceSpecificService>().ClearCookies();
Xamarin.Android implementation
[assembly: Dependency(typeof(DeviceSpecificService))]
namespace AnAwesomeCompany.AGreatProject.Presentation.Droid.Implementations
{
public class DeviceSpecificService : IDeviceSpecificService
{
public void ClearCookies()
{
Android.Webkit.CookieManager.Instance.RemoveAllCookie();
}
}
}
Xamarin.IOS implementation
[assembly: Dependency(typeof(DeviceSpecificService))]
namespace AnAwesomeCompany.AGreatProject.Presentation.IOS.Implementations
{
public class DeviceSpecificService : IDeviceSpecificService
{
public void ClearCookies()
{
NSHttpCookieStorage CookieStorage = NSHttpCookieStorage.SharedStorage;
foreach (var cookie in CookieStorage.Cookies)
CookieStorage.DeleteCookie(cookie);
}
}
}
Tags In
2 Comments
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Hi, I am András,
I am a seasoned software engineer from Budapest, Hungary with a strong focus on mobile app development using .NET MAUI and Xamarin.Forms. My expertise also extends to website building for my happy customers and other complex system designing. I am passionate about developing well-organized, maintainable software solutions.
[…] Xamarin.Forms: Clear cookies in WebViews (András Tóth) […]
[…] Xamarin.Forms: Clear cookies in WebViews (András Tóth) […]