6

I know about the existince of CookieManager, but how do I remove cookies of a domain only?

Can someone help me with some code fragment?

Pentium10
  • 204,586
  • 122
  • 423
  • 502

4 Answers4

12
public void clearCookies(String domain) {
    CookieManager cookieManager = CookieManager.getInstance();
    String cookiestring = cookieManager.getCookie(domain);
    String[] cookies =  cookiestring.split(";");
    for (int i=0; i<cookies.length; i++) {
        String[] cookieparts = cookies[i].split("=");
        cookieManager.setCookie(domain, cookieparts[0].trim()+"=; Expires=Wed, 31 Dec 2025 23:59:59 GMT");
    }
}
Tommy Leong
  • 2,509
  • 6
  • 30
  • 54
Tom Kincaid
  • 4,887
  • 6
  • 47
  • 72
  • "Expires" part of your answer saved my day. Thank you. – trante Aug 08 '14 at 21:47
  • 4
    From what research I've done, it seems you need to provide the domain and path when calling setCookie(). Passing in the domain alone doesn't work for me, and I can't find a way to obtain the paths of the cookies for a given domain -- just the names and values. – Mark McClelland Nov 11 '14 at 23:15
  • In the sample code, why is the expires date in the future? – Joe Bowbeer Apr 28 '16 at 02:24
  • Yeah, I guess you could make the date in the past too. – Tom Kincaid Apr 29 '16 at 23:57
  • Thanks @TomKincaid, your suggestion saved my day too. Btw, we no longer need CookieSyncManager as the webview will perform sync itself. And it's already deprecated in API Level 21. Read more here...https://developer.android.com/reference/android/webkit/CookieSyncManager – Tommy Leong Jul 27 '20 at 09:00
10

Call android.webkit.CookieManager's getCookie method to generate a RFC 2109 Cookie header for the URL or domain you are interested. Parse the cookie header to get a list of cookie names. For each cookie name, generate a RFC 2109 Set-Cookie header for that name that has an expiry date in the past and pass it into CookieManager's setCookie method. Although the API docs specify that setCookie ignores values that have expired, Android's current implementation actually flushes the cookie in this case. To guard against future implementations that do ignore expired values as specified in the documentation, check that the cookies were actually removed and perform some fallback behaviour if they haven't—CookieManager's removeAllCookie method may be useful for this fallback.

rpetrich
  • 32,196
  • 6
  • 66
  • 89
  • Is there any cookie parser in android that can help us with this? Or should we be just doing split() and all ourselves? – Sudarshan Bhat Aug 31 '12 at 05:34
  • @Enigma read the RFC, it describes the exact format the cookie string will be in. – rpetrich Sep 04 '12 at 01:16
  • 4
    yeah, if you could post some code, that would be great! – Francisco Corrales Morales Jun 02 '14 at 22:25
  • 1
    @Enigma To parse cookie headers use: http://developer.android.com/reference/java/net/HttpCookie.html – ballzak Feb 05 '16 at 05:55
  • did anyone get this to work? I tried going this route, but the cookie never get set with the expires tag. Also when you call removeExpirecookies, the cookie remains the same. – darewreck Jan 04 '17 at 22:30
  • @darewreck Faced the same issue. The cookie never gets set with expiry tag. While reading it back it always comes up and also on the string red the expiry tag is always missing. – bpr10 Aug 24 '17 at 09:00
3

Here is a code sample from an open source project. Maybe could help someone.

https://github.com/janrain/engage.android/blob/96f21b45738ef82a911e27d8a707aff3a1024d36/Jump/src/com/janrain/android/utils/WebViewUtils.java

private static void deleteWebViewCookiesForDomain(Context context, String domain, boolean secure) {
    CookieSyncManager csm = CookieSyncManager.createInstance(context);
    CookieManager cm = CookieManager.getInstance();

    /* http://code.google.com/p/android/issues/detail?id=19294 */
    if (AndroidUtils.SDK_INT >= 11) {
        // don't trim leading '.'s
    } else {
        /* Trim leading '.'s */
        if (domain.startsWith(".")) domain = domain.substring(1);
    }

    /* Cookies are stored by domain, and are not different for different schemes (i.e. http vs
     * https) (although they do have an optional 'secure' flag.) */
    domain = "http" + (secure ? "s" : "") + "://" + domain;
    String cookieGlob = cm.getCookie(domain);
    if (cookieGlob != null) {
        String[] cookies = cookieGlob.split(";");
        for (String cookieTuple : cookies) {
            String[] cookieParts = cookieTuple.split("=");

            /* setCookie has changed a lot between different versions of Android with respect to
             * how it handles cookies like these, which are set in order to clear an existing
             * cookie.  This way of invoking it seems to work on all versions. */
            cm.setCookie(domain, cookieParts[0] + "=;");

            /* These calls have worked for some subset of the the set of all versions of
             * Android:
             * cm.setCookie(domain, cookieParts[0] + "=");
             * cm.setCookie(domain, cookieParts[0]); */
        }
        csm.sync();
    }
}
monkeyM
  • 243
  • 3
  • 8
  • In my case, I just need to make sure the domain name is correct (start with a "."), it will reset all the cookie values to empty string. Works well. – monkeyM May 13 '15 at 08:47
  • I think there something wrong with this function. After I executed it for "twitter.com" and "api.twitter.com" Twitter doesn't load anymore (empty page on Android emulator 6.0). However, it works for Facebook. – Mikalai Daronin Jul 24 '17 at 12:19
1

I don't see anyway to do this in the API, but you can always dig into the real source code (open source is nice)... for example, I found this deleteCookies method in this class: WebViewDatabase which is part of the core of Android.

As you can see there... cookies are just rows into a SQLite Database... so if you can make this class work, at least you know how to do it by your self.

Cristian
  • 198,401
  • 62
  • 356
  • 264
  • I know this is a bit old, but I'm looking into this myself. Is there a possibility for conflicts if I modify the webview.db database myself? Are there thread safety and locking issues if the CookieSyncManager or a WebView accesses it while I am modifying it? – cottonBallPaws Apr 07 '11 at 17:57