How do you delete all the cookies for the current domain using JavaScript?
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();
}
}
})();
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.
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;';
}
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.
If you have access to the jquery.cookie plugin, you can erase all cookies this way:
for (var it in $.cookie()) $.removeCookie(it);
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;
}
}