By polarbear


2008-10-07 16:41:55 8 Comments

How do you delete all the cookies for the current domain using JavaScript?

18 comments

@B. Bohdan 2019-03-01 15:19:22

I have some more sophisticated and OOP-oriented cookie control module. It also contains deleteAll method to clear all existing cookie. Make notice that this version of deleteAll method has setting path=/ that causes deleting of all cookies within current domain. If you need to delete cookies only from some scope you will have to upgrade this method my adding dynamic path parameter to this method.

There is main Cookie class:

import {Setter} from './Setter';

export class Cookie {
    /**
     * @param {string} key
     * @return {string|undefined}
     */
    static get(key) {
        key = key.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1');

        const regExp = new RegExp('(?:^|; )' + key + '=([^;]*)');
        const matches = document.cookie.match(regExp);

        return matches
            ? decodeURIComponent(matches[1])
            : undefined;
    }

    /**
     * @param {string} name
     */
    static delete(name) {
        this.set(name, '', { expires: -1 });
    }

    static deleteAll() {
        const cookies = document.cookie.split('; ');

        for (let cookie of cookies) {
            const index = cookie.indexOf('=');

            const name = ~index
                ? cookie.substr(0, index)
                : cookie;

            document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
        }
    }

    /**
     * @param {string} name
     * @param {string|boolean} value
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     */
    static set(name, value, opts = {}) {
        Setter.set(name, value, opts);
    }
}

Cookie setter method (Cookie.set) is rather complex so I decomposed it into other class. There is code of this one:

export class Setter {
    /**
     * @param {string} name
     * @param {string|boolean} value
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     */
    static set(name, value, opts = {}) {
        value = Setter.prepareValue(value);
        opts = Setter.prepareOpts(opts);

        let updatedCookie = name + '=' + value;

        for (let i in opts) {
            if (!opts.hasOwnProperty(i)) continue;

            updatedCookie += '; ' + i;

            const value = opts[i];

            if (value !== true)
                updatedCookie += '=' + value;
        }

        document.cookie = updatedCookie;
    }

    /**
     * @param {string} value
     * @return {string}
     * @private
     */
    static prepareValue(value) {
        return encodeURIComponent(value);
    }

    /**
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     * @private
     */
    static prepareOpts(opts = {}) {
        opts = Object.assign({}, opts);

        let {expires} = opts;

        if (typeof expires == 'number' && expires) {
            const date = new Date();

            date.setTime(date.getTime() + expires * 1000);

            expires = opts.expires = date;
        }

        if (expires && expires.toUTCString)
            opts.expires = expires.toUTCString();

        return opts;
    }
}

@Mashiro 2018-05-11 11:28:07

I don't know why the first voted answer doesn't work for me.

As this answer said:

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!

So my idea is to add a Cookie version control with the full set of setting, getting, removing of cookies:

var cookie_version_control = '---2018/5/11';

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

function getCookie(name) {
    var nameEQ = name+cookie_version_control + "=";
    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 removeCookie(name) {   
    document.cookie = name+cookie_version_control+'=; Max-Age=-99999999;';  
}

@CruelEngine 2018-09-17 11:12:03

this saved me hours . deserves the upvote. `` let now = new Date(0);`` let expireTime = now.getTime(); now.setTime(expireTime); document.cookie =document.cookie+';expires='+now.toUTCString()+';path=/'; will get the cookies removed .

@sureshvignesh 2017-07-06 09:54:21

Jquery:

var cookies = $.cookie();
for(var cookie in cookies) {
$.removeCookie(cookie);
}

vanilla JS

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
}

@Ruchira 2017-09-17 22:26:03

This requires jQuery Cookie plugin. jQuery library doesn't have cookie() function.

@Robert J. Walker 2008-10-07 17:27:03

function deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}

Note that this code has two limitations:

  • It will not delete cookies with HttpOnly flag set, as the HttpOnly flag disables Javascript's access to the cookie.
  • It will not delete cookies that have been set with a Path value. (This is despite the fact that those cookies will appear in document.cookie, but you can't delete it without specifying the same Path value with which it was set.)

@PhiLho 2008-10-07 19:56:13

Nice one, but after experimenting, I found that a site can have only one cookie without =, and then it is a nameless cookie, you get its value actually. So if eqPos == 1, you should do name = "" instead, to erase the nameless value.

@Dan Fabulich 2011-04-12 19:11:47

Beware! If your cookies are configured to use a path or domain component, this handy snippet won't work.

@Robert J. Walker 2011-04-20 17:24:47

True. The snippet could be modified to ask you for those details; but this works for most cases.

@VUELA 2013-08-21 20:40:44

How would this be modified to include the path or domain info?

@Cerin 2014-04-24 20:08:43

Why is this so high? It doesn't work at all...

@Robert J. Walker 2014-04-25 20:47:55

@Cerin: While it may not have worked for you, it clearly works for a bunch of other people. Perhaps you have to adapt this code for path or domain issues.

@HerrimanCoder 2015-04-23 20:38:30

PHP cookie deletion == epic fail. This javascript solution == epic success!

@Aaron Gillion 2016-03-26 06:12:57

@Cerin the problem is in his expires statement. If you swap in the eraseCookie() function from this source, the above function works.

@user3638471 2016-05-24 21:52:00

Didn't investigate why, but my localhost cookies were not cleared. The one by Craig Smedley cleared them, though.

@Daniel Kucal 2017-05-31 14:20:07

At least in Chrome cookies are separated by "; ", so we have to trim() the additional space or split('; ') (by '; ') to make it work properly. I've proposed an edit.

@Warlike Chimpanzee 2017-06-29 21:50:58

We need a way to deal with obsolete but highly upvoted answers like this one.

@umar faraz 2018-03-21 05:13:30

Not able to delete the cookie for the first time @RobertJ.Walker

@1N5818 2018-04-11 17:16:04

This answer is 10 years old and doesn't work.

@ABPerson 2019-03-31 13:42:05

If this doesn't work for you - try putting a .trim() at the end of the var cookie = line, and put ;path=/ at the end of the string on the document.cookie = line.

@Jacob David C. Cunningham 2017-05-24 16:52:29

An answer influenced by both second answer here and W3Schools

document.cookie.split(';').forEach(function(c) {
  document.cookie = c.trim().split('=')[0] + '=;' + 'expires=Thu, 01 Jan 1970 00:00:00 UTC;';
});

Seems to be working

edit: wow almost exactly the same as Zach's interesting how Stack Overflow put them next to each other.

edit: nvm that was temporary apparently

@Zach Shallbetter 2013-07-23 19:28:58

Figured I'd share this method for clearing cookies. Perhaps it may be helpful for someone else at some point.

var cookie = document.cookie.split(';');

for (var i = 0; i < cookie.length; i++) {

    var chip = cookie[i],
        entry = chip.split("="),
        name = entry[0];

    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

@SpYk3HH 2017-01-13 18:25:39

After testing almost ever method listed in multiple style of browsers on multiple styles of cookies, I found almost nothing here works even 50%.

Please help correct as needed, but I'm going to throw my 2 cents in here. The following method breaks everything down and basically builds the cookie value string based on both the settings pieces as well as including a step by step build of the path string, starting with / of course.

Hope this helps others and I hope any criticism may come in the form of perfecting this method. At first I wanted a simple 1-liner as some others sought, but JS cookies are one of those things not so easily dealt with.

;(function() {
    if (!window['deleteAllCookies'] && document['cookie']) {
        window.deleteAllCookies = function(showLog) {
            var arrCookies = document.cookie.split(';'),
                arrPaths = location.pathname.replace(/^\//, '').split('/'), //  remove leading '/' and split any existing paths
                arrTemplate = [ 'expires=Thu, 01-Jan-1970 00:00:01 GMT', 'path={path}', 'domain=' + window.location.host, 'secure=' ];  //  array of cookie settings in order tested and found most useful in establishing a "delete"
            for (var i in arrCookies) {
                var strCookie = arrCookies[i];
                if (typeof strCookie == 'string' && strCookie.indexOf('=') >= 0) {
                    var strName = strCookie.split('=')[0];  //  the cookie name
                    for (var j=1;j<=arrTemplate.length;j++) {
                        if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
                        else {
                            var strValue = strName + '=; ' + arrTemplate.slice(0, j).join('; ') + ';';  //  made using the temp array of settings, putting it together piece by piece as loop rolls on
                            if (j == 1) document.cookie = strValue;
                            else {
                                for (var k=0;k<=arrPaths.length;k++) {
                                    if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
                                    else {
                                        var strPath = arrPaths.slice(0, k).join('/') + '/'; //  builds path line 
                                        strValue = strValue.replace('{path}', strPath);
                                        document.cookie = strValue;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            showLog && window['console'] && console.info && console.info("\n\tCookies Have Been Deleted!\n\tdocument.cookie = \"" + document.cookie + "\"\n");
            return document.cookie;
        }
    }
})();

@adelriosantiago 2018-12-11 13:50:32

Not working either, or at least not for me... I had to delete the cookies by HTTP.

@Stefano Saitta 2016-07-07 11:31:05

Functional Approach + ES6

const cookieCleaner = () => {
  return document.cookie.split(";").reduce(function (acc, cookie) {
    const eqPos = cookie.indexOf("=");
    const cleanCookie = `${cookie.substr(0, eqPos)}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;`;
    return `${acc}${cleanCookie}`;
  }, "");
}

Note: Doesn't handle paths

@Shubham Kumar 2016-07-04 11:55:08

Here's a simple code to delete all cookies in JavaScript.

function deleteAllCookies(){
   var cookies = document.cookie.split(";");
   for (var i = 0; i < cookies.length; i++)
     deleteCookie(cookies[i].split("=")[0]);
}

function setCookie(name, value, expirydays) {
 var d = new Date();
 d.setTime(d.getTime() + (expirydays*24*60*60*1000));
 var expires = "expires="+ d.toUTCString();
 document.cookie = name + "=" + value + "; " + expires;
}

function deleteCookie(name){
  setCookie(name,"",-1);
}

Run the function deleteAllCookies() to clear all cookies.

@Derek Wade 2016-02-28 08:09:45

I found a problem in IE and Edge. Webkit browsers (Chrome, safari) seem to be more forgiving. When setting cookies, always set the "path" to something, because the default will be the page that set the cookie. So if you try to expire it on a different page without specifying the "path", the path won't match and it won't expire. The document.cookie value doesn't show the path or expiration for a cookie, so you can't derive where the cookie was set by looking at the value.

If you need to expire cookies from different pages, save the path of the setting page in the cookie value so you can pull it out later or always append "; path=/;" to the cookie value. Then it will expire from any page.

@Jan 2015-10-27 10:59:23

And here's one to clear all cookies in all paths and all variants of the domain (www.mydomain.com, mydomain.com etc):

(function () {
    var cookies = document.cookie.split("; ");
    for (var c = 0; c < cookies.length; c++) {
        var d = window.location.hostname.split(".");
        while (d.length > 0) {
            var cookieBase = encodeURIComponent(cookies[c].split(";")[0].split("=")[0]) + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain=' + d.join('.') + ' ;path=';
            var p = location.pathname.split('/');
            document.cookie = cookieBase + '/';
            while (p.length > 0) {
                document.cookie = cookieBase + p.join('/');
                p.pop();
            };
            d.shift();
        }
    }
})();

@Kanan Farzali 2017-11-20 14:26:44

this should be the best answer

@Orny 2018-03-11 16:31:24

This one works for me in chrome, while the accepted answer doesn't

@Velojet 2018-05-06 22:09:22

Brilliant! After trying several others which worked on my dev server but not on the production server, this was the first to work on both. Pure gold!

@joseantgv 2018-05-11 08:53:43

It works like a charm, you made my day

@Roman 2015-08-13 09:57:26

//Delete all cookies
function deleteAllCookies() {
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + '=;' +
            'expires=Thu, 01-Jan-1970 00:00:01 GMT;' +
            'path=' + '/;' +
            'domain=' + window.location.host + ';' +
            'secure=;';
    }
}

@Craig Smedley 2014-12-09 08:28:21

One liner

In case you want to paste it in quickly...

document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });

And the code for a bookmarklet :

javascript:(function(){document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); }); })();

@AnthonyVO 2011-05-04 16:34:52

After a bit of frustration with this myself I knocked together this function which will attempt to delete a named cookie from all paths. Just call this for each of your cookies and you should be closer to deleting every cookie then you were before.

function eraseCookieFromAllPaths(name) {
    // This function will attempt to remove a cookie from all paths.
    var pathBits = location.pathname.split('/');
    var pathCurrent = ' path=';

    // do a simple pathless delete first.
    document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;';

    for (var i = 0; i < pathBits.length; i++) {
        pathCurrent += ((pathCurrent.substr(-1) != '/') ? '/' : '') + pathBits[i];
        document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;' + pathCurrent + ';';
    }
}

As always different browsers have different behaviour but this worked for me. Enjoy.

@UKDataGeek 2016-05-07 12:24:40

worked for me using Ga cookie.

@AnthonyVO 2016-12-12 15:23:17

@TomHammond, That should be a completely new question. The primary issues are around the hosted domain vs hosting domain and your ability to control the hosted page.

@Sunny R Gupta 2017-06-05 13:33:16

This will still not remove httpOnly cookies. They can only be modified over HTTP.

@jichi 2014-01-06 09:38:36

If you have access to the jquery.cookie plugin, you can erase all cookies this way:

for (var it in $.cookie()) $.removeCookie(it);

@Cerin 2014-04-24 20:40:34

This does not work.

@jichi 2014-04-24 23:28:17

I just tried it on my own website, which deleted all cookies. Could @Cerin sama try executing the following code in the console before and after clearing cookies? "for (var it in $.cookie()) console.log(it);"

@Brimby 2015-04-07 18:21:16

This absolutely worked, and is awesome.

@ko1Rn 2017-11-07 08:55:46

jichi did you include the jquery library along side with jquery.cookie plugin?

@Dinesh 2013-11-21 08:09:33

Simpler. Faster.

function deleteAllCookies() {
 var c = document.cookie.split("; ");
 for (i in c) 
  document.cookie =/^[^=]+/.exec(c[i])[0]+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT";    
}

@Scott Smith 2016-02-11 17:42:07

Doesn't handle paths.

@UKDataGeek 2016-05-07 12:21:25

didn't work for ga cookie

@Sec 2008-10-07 16:54:27

You can get a list by looking into the document.cookie variable. Clearing them all is just a matter of looping over all of them and clearing them one by one.

@ConroyP 2008-10-07 16:49:25

As far as I know there's no way to do a blanket delete of any cookie set on the domain. You can clear a cookie if you know the name and if the script is on the same domain as the cookie.

You can set the value to empty and the expiration date to somewhere in the past:

var mydate = new Date();
mydate.setTime(mydate.getTime() - 1);
document.cookie = "username=; expires=" + mydate.toGMTString(); 

There's an excellent article here on manipulating cookies using javascript.

@matt b 2011-06-15 14:15:22

You can also just do document.cookie="username;expires=" + new Date(0).toGMTString() - not much difference if the cookie expires 1 second ago or in 1970

@bjorkland 2017-03-24 15:41:15

Thank you for the article!

Related Questions

Sponsored Content

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

38 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

52 Answered Questions

[SOLVED] Create GUID / UUID in JavaScript?

  • 2008-09-19 20:01:00
  • Jason Cohen
  • 1587474 View
  • 3807 Score
  • 52 Answer
  • Tags:   javascript guid uuid

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

3 Answered Questions

84 Answered Questions

[SOLVED] How to validate an email address in JavaScript

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

56 Answered Questions

[SOLVED] How to replace all occurrences of a string?

57 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

Sponsored Content