András Tóth‘s professional blog
banditoth.net

Hey there 👋, I’m banditoth a .NET MAUI developer from Hungary.
I write about software development with .NET technologies.

You can find me on:
LinkedIn | Github | StackOverflow | X / Twitter | Threads

Xamarin.Forms: Clear cookies in WebViews

This content has 3 years. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.

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);
		}
	}
}

2 responses to “Xamarin.Forms: Clear cookies in WebViews”

  1. […] Xamarin.Forms: Clear cookies in WebViews (András Tóth) […]

  2. […] Xamarin.Forms: Clear cookies in WebViews (András Tóth) […]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.