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

2 thoughts on “Xamarin.Forms: Clear cookies in WebViews”

Leave a Comment

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