Possible to disable caching in WebView?

RyanWatsonRyanWatson USMember ✭✭✭
I need to be able to disable caching from the WebView, is that possible to do in Forms or even with a custom renderer?
Tagged:

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    Use Dependency Service to clear caches on each platform.
    Define an interface in your Forms project:

    namespace Demo
    {
        public interface ICacheManager
        {
            void Clear();
        }
    }
    

    Implementation on iOS:

    [assembly: Dependency(typeof(CacheManagerImplementation))]
    namespace Demo.iOS
    {
        public class CacheManagerImplementation : ICacheManager
        {
            public void Clear()
            {
                NSHttpCookieStorage CookieStorage = NSHttpCookieStorage.SharedStorage;
                foreach (var cookie in CookieStorage.Cookies)
                    CookieStorage.DeleteCookie(cookie);
            }
        }
    }
    

    Android:

    [assembly: Dependency(typeof(CacheManagerImplementation))]
    namespace Demo.Droid
    {
        public class CacheManagerImplementation : ICacheManager
        {
            public void Clear()
            {
                var cookieManager = CookieManager.Instance;
                cookieManager.RemoveAllCookie();
            }
        }
    }
    

    Add the code below when you want to load a new source using webview:
    DependencyService.Get<ICacheManager>().Clear();
    Or for Android you could create a custom renderer for your custom webview:

    public class MyCustomWebViewRenderer : WebViewRenderer
    {
        public MyCustomWebViewRenderer(Context context) : base(context)
        {
        }
    
        protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
        {
            base.OnElementChanged(e);
    
            Control.Settings.SetAppCacheEnabled(false);
            Control.Settings.CacheMode = Android.Webkit.CacheModes.NoCache;
        }
    }
    
Sign In or Register to comment.