How to Delete All Cookies with JavaScript

Clearing all cookies with JavaScript

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.)

How can I delete all cookies with JavaScript?

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.

Delete all Cookies of browser using javascript

You cannot delete cookies via Javascript that come from other domains than the page you are currently on. This is a browser security feature. And, if a cookie is marked for a particular path, you can only access it from a page on that particular path (even from the same domain).

And, for cookies that are marked HttpOnly (e.g. server-side access only cookies), you can't even delete those for your own domain via javascript.

The only way to clear all cookies is for you (the user) to use the browser's user interface to delete the cookies or to configure your browser to automatically clear cookies when you close the browser.

Clearing all cookies with JavaScript

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.)


Related Topics



Leave a reply



Submit