Clearing all cookies with JavaScript

javascript

You can clear all cookies using JavaScript by iterating through all cookies using the document.cookie property and deleting each one individually. Here’s an example:

function clearAllCookies() {
  // Split cookie string and remove all cookies
  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";
  }
}

In this example, we define a function called clearAllCookies() that iterates through all cookies using the document.cookie property. For each cookie, we extract the name and set its expiration date to a date in the past, effectively deleting it. Finally, the function can be called whenever you need to clear all cookies, for example:

// Call clearAllCookies() function to clear all cookies
clearAllCookies();

Note that this method will only clear cookies for the current domain. If you want to clear cookies for a specific domain, you can include the domain parameter in the expires attribute, like this:

document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;domain=mydomain.com";

Replace mydomain.com with the domain for which you want to clear cookies.