Clearing all cookies with JavaScript
Asked Answered
D

27

431

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

Dynatron answered 7/10, 2008 at 16:41 Comment(1)
Another way to do this (outside of JS) is with this answer: https://mcmap.net/q/81977/-how-to-delete-all-cookies-of-my-website-in-php - it's PHP based, but an option for those who use PHP.Longoria
V
443
function deleteAllCookies() {
    const cookies = document.cookie.split(";");

    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i];
        const eqPos = cookie.indexOf("=");
        const 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.)
Viddah answered 7/10, 2008 at 17:27 Comment(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.Dunant
Beware! If your cookies are configured to use a path or domain component, this handy snippet won't work.Draff
True. The snippet could be modified to ask you for those details; but this works for most cases.Viddah
How would this be modified to include the path or domain info?Humfried
@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.Viddah
PHP cookie deletion == epic fail. This javascript solution == epic success!Episcopalism
@Cerin the problem is in his expires statement. If you swap in the eraseCookie() function from this source, the above function works.Keare
Didn't investigate why, but my localhost cookies were not cleared. The one by Craig Smedley cleared them, though.Twelve
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.Varletry
We need a way to deal with obsolete but highly upvoted answers like this one.Alleneallentown
Not able to delete the cookie for the first time @RobertJ.WalkerBreeding
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.Bulwerlytton
the comment by @Bulwerlytton about trim and path=/ saves the day! Thank you very muchBlearyeyed
P
203

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=/"); }); })();
Pissed answered 9/12, 2014 at 8:28 Comment(4)
Some persistant web sites backup cookies in localStorage so window.localStorage.clear() may be helpful as wellSabadell
The official answer comes with 2 limitations, does this answer solve them?Futch
This isn't clearing cookies in Brave. It is, however, clearing site data which is something I've been looking for. Thanks for sharing.Waggery
@Futch no, as far as I know, Javascript can't remove those cookies at all (unless you know the "path" for those with that)Redintegrate
R
161

And here's one to clear all cookies in all paths and all variants of the domain (www.mydomain.example, mydomain.example 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();
        }
    }
})();
Retentive answered 27/10, 2015 at 10:59 Comment(10)
this should be the best answerKoeppel
This one works for me in chrome, while the accepted answer doesn'tMarola
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!Bifarious
This also for me works much better than accepted answer. thanksShulamite
Had to add code for domain with leading dot, some of my cookies have it, some don't, even though there are no relevant subdomains. But with those changes, it works well for me, the most complete implementation I've tried so far.Gallop
The official answer comes with 2 limitations, does this answer solve them?Futch
This function affects php sessions, at least in Edge.Ripuarian
This is not working with latest version of chrome event if the expiration date is set...Palmette
Between this and the answer above, it covered what I was looking for. Thanks for sharing.Waggery
Had to add removing the cookies with empty domain and empty path to cover all my cases.Cordite
V
81

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.

Vaishnava answered 4/5, 2011 at 16:34 Comment(2)
@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.Vaishnava
This will still not remove httpOnly cookies. They can only be modified over HTTP.Rubel
G
16

The following code will remove all cookies within the current domain and all trailing subdomains (www.some.sub.domain.example, .some.sub.domain.example, .sub.domain.example and so on.).

A single line vanilla JS version (I think the only one here without the use of cookie.split()):

document.cookie.replace(/(?<=^|;).+?(?=\=|;|$)/g, name => location.hostname.split('.').reverse().reduce(domain => (domain=domain.replace(/^\.?[^.]+/, ''),document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`,domain), location.hostname));

This is a readable version of this single line:

document.cookie.replace(
  /(?<=^|;).+?(?=\=|;|$)/g,
  name => location.hostname
    .split(/\.(?=[^\.]+\.)/)
    .reduceRight((acc, val, i, arr) => i ? arr[i]='.'+val+acc : (arr[i]='', arr), '')
    .map(domain => document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`)
);
Gerstner answered 18/3, 2021 at 19:43 Comment(3)
Only solution here that worked for me (including google analytics cookies)! Thank you very much.Heurlin
This works on chrome but produces and error on iOS and safari, "SyntaxError: Invalid regular expression: invalid group specifier name"Cortese
Watch out with this one! As Mike said, this breaks on iOS and produced a lot of issues for me.Unadvised
G
13

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

Gael answered 24/5, 2017 at 16:52 Comment(0)
M
13

If you are concerned about clearing cookies only on a secured origin you can use the Cookie Store API and it's .delete() method.

cookieStore.getAll().then(cookies => cookies.forEach(cookie => {
    console.log('Cookie deleted:', cookie);
    cookieStore.delete(cookie.name);
}));

Visit the caniuse.com table for the Cookie Store API to check for browser support.

Marqueritemarques answered 13/3, 2021 at 9:48 Comment(2)
please note that as of today this works only on latest version of Chrome.Monty
Something may have changed, I had to do this: cookieStore.delete(cookie) if I gave it just the cookie.name it didn't work, but it works if I gave the object. For example here is how to clear all cookies: cookieStore.getAll().then(p => p.forEach(c => cookieStore.delete(c)))Ukulele
B
12

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

for (var it in $.cookie()) $.removeCookie(it);
Ba answered 6/1, 2014 at 9:38 Comment(2)
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);"Ba
jichi did you include the jquery library along side with jquery.cookie plugin?Ent
G
11

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.

Gabriello answered 7/10, 2008 at 16:49 Comment(2)
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 1970Pleonasm
It will not delete cookies that have been set with a Path value.Futch
K
7

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";    
}
Kelp answered 21/11, 2013 at 8:9 Comment(1)
Doesn't handle paths.Ammamaria
I
5
document.cookie.split(";").forEach(function(c) { 
    document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
});
//clearing local storage
localStorage.clear();
Ivanovo answered 1/3, 2021 at 12:21 Comment(3)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Merciless
thanks for your valid information. I appreciate itIvanovo
It will not delete cookies that have been set with a Path value.Futch
P
4

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;';
}
Penna answered 23/7, 2013 at 19:28 Comment(1)
It will not delete cookies that have been set with a Path value.Futch
C
4

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;';  
}
Cheap answered 11/5, 2018 at 11:28 Comment(1)
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 .Eggers
K
4

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;
    }
}
Kekkonen answered 1/3, 2019 at 15:19 Comment(0)
S
2
//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=;';
    }
}
Shaunna answered 13/8, 2015 at 9:57 Comment(1)
It will not delete cookies that have been set with a Path value.Futch
T
2

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.

Tortoiseshell answered 4/7, 2016 at 11:55 Comment(1)
It will not delete cookies that have been set with a Path value.Futch
D
2

I'm contributing here because this function will allow you to delete all cookies (matching the path, by default no-path or \) also cookies that were set to be included on subdomains

function clearCookies( wildcardDomain=false, primaryDomain=true, path=null ){
  pathSegment = path ? '; path=' + path : ''
  expSegment = "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"
  document.cookie.split(';').forEach(
    function(c) { 
      primaryDomain && (document.cookie = c.replace(/^ +/, "").replace(/=.*/, expSegment + pathSegment))
      wildcardDomain && (document.cookie = c.replace(/^ +/, "").replace(/=.*/, expSegment + pathSegment + '; domain=' + document.domain))
    }
  )
} 
Dour answered 22/6, 2021 at 14:9 Comment(0)
E
1

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.

Esque answered 7/10, 2008 at 16:54 Comment(0)
E
1

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

Exorcise answered 7/7, 2016 at 11:31 Comment(0)
C
1

Several answers here do not resolve the path question. I believe that: if you control the site, or part of it, you should know all the paths used. So you just have to have it delete all cookies from all paths used. Because my site already has jquery (and out of laziness) I decided to use the jquery cookie, but you can easily adapt it to pure javascript based on the other answers.

In this example I remove three specific paths that were being used by the ecommerce platform.

let mainURL = getMainURL().toLowerCase().replace('www.', '').replace('.com.br', '.com'); // i am a brazilian guy
let cookies = $.cookie();
for(key in cookies){
    // default remove
    $.removeCookie(key, {
        path:'/'
    });
    // remove without www
    $.removeCookie(key, {
        domain: mainURL,
        path: '/'
    });
    // remove with www
    $.removeCookie(key, {
        domain: 'www.' + mainURL,
        path: '/'
    });
};

// get-main-url.js v1
function getMainURL(url = window.location.href){
    url = url.replace(/.+?\/\//, ''); // remove protocol
    url = url.replace(/(\#|\?|\/)(.+)?/, ''); // remove parameters and paths
    // remove subdomain
    if( url.split('.').length === 3 ){
        url = url.split('.');
        url.shift();
        url = url.join('.');
    };
    return url;
};

I changed the .com site to .com.br because my site is multi domain and multi lingual

Compulsive answered 28/2, 2021 at 17:50 Comment(0)
M
1

This works for me:

function deleteCookie(name) {
  document.cookie = 
    `${name}=; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Path=/`;

    // Remove it from local storage too
    window.localStorage.removeItem(name);
}

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

  cookies.forEach((cookie) => {
    const name = cookie.split("=").shift();
    this.deleteCookie(name);
  });

  // Some sites backup cookies in `localStorage`
  window.localStorage.clear();
}
Maternal answered 14/12, 2022 at 15:31 Comment(0)
L
0

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
}
Lyndalynde answered 6/7, 2017 at 9:54 Comment(2)
This requires jQuery Cookie plugin. jQuery library doesn't have cookie() function.Voussoir
And it will not delete cookies that have been set with a Path value.Futch
S
0

If you'd like to use js-cookie npm package and remove cookies by name:

import cookie from 'js-cookie'

export const removeAllCookiesByName = (cookieName: string) => {
  const hostParts = location.host.split('.')
  const domains = hostParts.reduce(
    (acc: string[], current, index) => [
      ...acc,
      hostParts.slice(index).join('.'),
    ],
    []
  )
  domains.forEach((domain) => cookie.remove(cookieName, { domain }))
}

Steatopygia answered 15/12, 2021 at 8:35 Comment(0)
H
0

We can do it like so:

deleteAllCookies=()=>
      {
      let c=document.cookie.split(';')
      for(const k of c)
         {
         let s=k.split('=')
         document.cookie=s[0].trim()+'=;expires=Fri, 20 Aug 2021 00:00:00 UTC'
         }
      }

Usage:

deleteAllCookies()
  • the expiration date was a random day prior to this answer; it can be any date before the current day
  • In JS you cannot read through cookies based on path
  • In JS you can only set or get cookies
Hearn answered 11/8, 2022 at 5:5 Comment(0)
A
0

This is variation of one of the answers above. If argument (cookieName) is passed, the function removes this given cookie in all subdomains and higher level domains (except TLD). If no argument is passed function deletes all cookies in all domains (except TLD).

deleteCookie = function(cookieName) {
            var cookies = document.cookie.split("; ");
            for (var c = 0; c < cookies.length; c++) {
                var d = window.location.hostname.split(".");
                while (d.length > 1) {
                    if (cookieName) {
                        var cookie = cookieName;
                        c = cookies.length;
                    } else {
                        var cookie = cookies[c].split(";")[0].split("=")[0];
                    }
                    var cookieBase = encodeURIComponent(cookie) + '=; 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();
                }
            }
        };
Alida answered 30/5, 2023 at 20:23 Comment(0)
C
-1

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.

Contribute answered 28/2, 2016 at 8:9 Comment(0)
H
-1

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;
        }
    }
})();
Helmand answered 13/1, 2017 at 18:25 Comment(1)
Not working either, or at least not for me... I had to delete the cookies by HTTP.Doorstep

© 2022 - 2024 — McMap. All rights reserved.