How to clear cookies and cache of webview on Android when not in webview?
Asked Answered
D

5

82

Upon a user's sign out from my app I am clearing everything that may have been cached previously from the webview by calling this method:

 public void clearCookiesAndCache(Context context){
    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        cookieManager.removeAllCookies(null);
    }
    else {
        cookieManager.removeAllCookie();
    }        
}

CookieSyncManager is marked as deprecated, however. CookieSyncManager.createInstance(context) is necessary to be called, however, if you have not loaded the webview previously. So how are we supposed to clear the cookies and cache without using the deprecated CookieSyncManager in cases where the webview may not have been previously loaded?

Deceive answered 11/3, 2015 at 22:1 Comment(3)
How do you clear the cache without a WebView instance? You are supposed to use WebView.clearCache for that, which isn't static.Voyeurism
@MikhailNaganov WebView.clearCache doesn't seem to clear the cookies though.Steamroller
Did you ever find a solution for this problem?Lilongwe
R
168

I use the following approach in my app:

    @SuppressWarnings("deprecation")
    public static void clearCookies(Context context)
    {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            Log.d(C.TAG, "Using clearCookies code for API >=" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
            CookieManager.getInstance().removeAllCookies(null);
            CookieManager.getInstance().flush();
        } else
        {
            Log.d(C.TAG, "Using clearCookies code for API <" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
            CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(context);
            cookieSyncMngr.startSync();
            CookieManager cookieManager=CookieManager.getInstance();
            cookieManager.removeAllCookie();
            cookieManager.removeSessionCookie();
            cookieSyncMngr.stopSync();
            cookieSyncMngr.sync();
        }
    }

Or in Kotlin

@SuppressWarnings("deprecation")
fun clearCookies(context: Context?) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        CookieManager.getInstance().removeAllCookies(null)
        CookieManager.getInstance().flush()
    } else if (context != null) {
        val cookieSyncManager = CookieSyncManager.createInstance(context)
        cookieSyncManager.startSync()
        val cookieManager: CookieManager = CookieManager.getInstance()
        cookieManager.removeAllCookie()
        cookieManager.removeSessionCookie()
        cookieSyncManager.stopSync()
        cookieSyncManager.sync()
    }
}

I call this method in the following manner from my fragment:

mWebView.clearCache(true);
mWebView.clearHistory();
    
U.clearCookies(getActivity());
    
mWebView.loadUrl(authorizeURL);

It is possible to dump the cookies for a domain before and after the call to clearCookies by

String yahooCookies = CookieManager.getInstance().getCookie("https://yahoo.com");
Log.d(C.TAG, "Cookies for yahoo.com:" + yahooCookies);

After calling clearCookies yahooCookies will be null.

This implementation feeds my needs, I have tested it on several emulators and a prehistoric Samsung Galaxy Gio with Android 2.3.3 and Nexus 5 with Android 5.1.1.

Rica answered 11/8, 2015 at 19:54 Comment(9)
you have +1 from me, 10x about this code, but please change the the first letter of ClearCookies to be lower case (clearCookies) this is JavaVarion
Your code snippet has worked like god for us. I have been struggling with webview cache issue. Clearing cache did not work but clearing cookies worked. Thanks alot!!!!!!!! I was facing issue in integration ccavenue payment gateway issue in webview.Montagnard
Thanks man!!!!! You saved my day.This solution working awesome.. Once thanks a lotSoulier
I was getting crashes on devices running SDK 21. CookieSyncManger was deprecated on 21 -> developer.android.com/reference/android/webkit/…. Should be "Build.VERSION_CODES.LOLLIPOP"Buie
Hi! What's the purpose of calling CookieManager.getInstance().flush(); ? according to documentation developer.android.com/reference/android/webkit/… it's not related to clearing cookies...Revis
Since removeAllCookies is an async operation, should we call flush inside removeAllCookies' callback?Whitehead
Good Solution ! ThanksDrusy
Why exactly the check for LOLLIPOP_MR1 (API 22) instead of LOLLIPOP (API 21)? All those apis seems to have been added in API 21 so I wondered if there was a particular reason for checking for 22 instead?Seleneselenious
I can't thank you enough for this! WebView API is absolutely terrible, they should definitely refactor itCaprifoliaceous
C
24

Working and tested ..

android.webkit.CookieManager cookieManager = CookieManager.getInstance();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
       cookieManager.removeAllCookies(new ValueCallback<Boolean>() {
         // a callback which is executed when the cookies have been removed
         @Override
         public void onReceiveValue(Boolean aBoolean) {
               Log.d(TAG, "Cookie removed: " + aBoolean);
         }
       });
}
else cookieManager.removeAllCookie();
Corrugate answered 22/12, 2015 at 7:49 Comment(3)
@Boonie yup it shouldCorrugate
But has it been tested on them? Wouldn't any device still using CookieSyncManager not work correctly with this, or is there some appcompat style approach going on behind the scenes of CookieManager.removeAllCookies()?Boonie
Works well on ICS and Android 6.0Crockery
C
17

To clear all the stored info from Webview,

// Clear all the Application Cache, Web SQL Database and the HTML5 Web Storage
    WebStorage.getInstance().deleteAllData();

    // Clear all the cookies
    CookieManager.getInstance().removeAllCookies(null);
    CookieManager.getInstance().flush();

    webView.clearCache(true);
    webView.clearFormData();
    webView.clearHistory();
    webView.clearSslPreferences();
Cupro answered 28/1, 2020 at 10:36 Comment(1)
Thank you. WebStorage.getInstance().deleteAllData() Did the trick for me. It would otherwise get stuck at some weird point.Molest
Y
7

I'm using this...

@WorkerThread
public static void clearCache() {
    new WebView(getApplicationContext()).clearCache(true);
}

Be careful to call it on a UI Thread otherwise you get an exception.

Yoshieyoshiko answered 22/6, 2015 at 10:16 Comment(2)
About how to get application context, refer to #987572Yoshieyoshiko
Awesome! For me, cookieManager.removeAllCookies() never worked. The boolean value received was always false. But doing this way worked like a charm!!Arterial
P
4

I just had the same problem. I needed to delete all cookies because I didn't want to keep old ones and didn't want to use the deprecated method.

Here the documentation:

http://developer.android.com/reference/android/webkit/CookieManager.html

And here the method:

public abstract void removeAllCookies (ValueCallback callback)

In your case:

cookieManager.removeAllCookies(null);

should do the job. If with "null" it doesn't work, then you have to use a callback*...

Eventually you may find an answer here: Android WebView Cookie Problem

Hope this helps. Cheers

Paderewski answered 12/5, 2015 at 11:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.