77

I have written code to save cookies in JavaScript. Now I need to clear the cookies irrespective of values that I assigned.

Are there any script modules to delete all cookies that were generated by Javascript?

My Sample Code:

document.cookie = 'ppkcookie2=another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

How else could I clear all of the cookies?

Will there will be any problems when I test the code on the webserver?

Community
  • 1
  • 1
venkatachalam
  • 102,353
  • 31
  • 72
  • 77

4 Answers4

86

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};
jb.
  • 9,987
  • 12
  • 39
  • 38
  • 1
    cool function! There is a little typo though. There should only be one '+' between "expires=" and new Date :) – Andbdrew Nov 28 '11 at 22:46
  • 41
    @Andbdrew That's not a typo. Appending a `+` in front of any variable in JavaScript converts it into a number. Without that you will get the date in string format since the `+` operator is used as string concatenation operator here while what you really want is the Unix timestamp – Yi Jiang Dec 03 '11 at 13:38
  • This answers the question better than the accepted answer. Very pertinent information. – Andrew Ensley Nov 29 '12 at 19:19
  • @jb - since you have the domain info included here, is there any chance that this can list cookies set with a domain other than the site's own domain? – VUELA Aug 22 '13 at 03:56
  • @VUELA using the function I provided you can only clear cookies related to the TLD of the window. You cannot clear cookies on other domains. You may find this article from GitHub interesting: https://github.com/blog/1466-yummy-cookies-across-domains – jb. Aug 22 '13 at 19:45
  • note: You can see the domain and path of cookies in Chrome Developer Tools -> network tab -> cookies sub-tab. – bnieland Mar 06 '20 at 15:35
72

On the face of it, it looks okay - if you call eraseCookie() on each cookie that is read from document.cookie, then all of your cookies will be gone.

Try this:

var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
  eraseCookie(cookies[i].split("=")[0]);

All of this with the following caveat:

  • JavaScript cannot remove cookies that have the HttpOnly flag set.
blizzrdof77
  • 363
  • 4
  • 14
Guss
  • 30,470
  • 17
  • 104
  • 128
  • 3
    "You can only remove cookies created by JavaScript - if a cookie was create by the server, then you cannot remove it through JavaScript." Actually, you should be able to erase any cookies you can see. – Powerlord Feb 27 '09 at 15:40
  • I can't find the exact reference right now, but I've had some problems in client manipulations of cookies created by a server. I do believe that there are some issues with that at least on Firefox. – Guss Feb 27 '09 at 16:27
  • 26
    It's the "HttpOnly" flag that is catching you up. You CAN delete server cookies from javascript unless they are protected with the HttpOnly flag – Eli Aug 03 '10 at 19:14
  • 1
    Thanks for the explanation. The name is not really intuitive, I think. – Guss Aug 22 '10 at 07:54
  • 1
    I edited the final sentence in the answer for accuracy so the comments above are now redundant. – Cory House Jan 01 '12 at 13:38
  • If you are working on a site like dev.foobar.com how can you erase a cookie set as domain .foobar.com ? Can this JS be modified to be able to do that? – BuddyJoe Jan 11 '12 at 18:25
  • As far as I understand, if the browser decides that a cookie is relevant to your current domain, regardless where it was set, then you can read it in document.cookie. And if the cookie is not HttpOnly, then you can also delete it with the above code example. – Guss Jan 15 '12 at 09:26
  • excellent..great.. :) – Arunjith R S Aug 14 '18 at 12:59
  • why would anyone use `HttpOnly`, though? – france1 Jan 27 '23 at 17:56
  • Why do people use `private` specifier on object methods? Because they lack trust. – Guss Jul 02 '23 at 08:19
10

This is a function we are using in our application and it is working fine.

delete cookie: No argument method

function clearListCookies()
{   
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++)
    {   
        var spcook =  cookies[i].split("=");
        deleteCookie(spcook[0]);
    }
    function deleteCookie(cookiename)
    {
        var d = new Date();
        d.setDate(d.getDate() - 1);
        var expires = ";expires="+d;
        var name=cookiename;
        //alert(name);
        var value="";
        document.cookie = name + "=" + value + expires + "; path=/acc/html";                    
    }
    window.location = ""; // TO REFRESH THE PAGE
}

Edit: This will delete the cookie by setting it to yesterday's date.

antnewbee
  • 1,779
  • 4
  • 25
  • 38
5

Why do you use new Date instead of a static UTC string?

    function clearListCookies(){
    var cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++){   
            var spcook =  cookies[i].split("=");
            document.cookie = spcook[0] + "=;expires=Thu, 21 Sep 1979 00:00:01 UTC;";                                
        }
    }
pykiss
  • 949
  • 12
  • 15