Sometimes, we may clear all the cookies stored in the browser for the given site.
In this article, we’ll look at how to clear all cookies with JavaScript.
Setting the Expiry Date of All Cookies to a Date Earlier than the Current Date-Time
We can clear all cookies with JavaScript by setting the expiry date of each cookie to a date and time that’s earlier than the current time.
To do this, we write:
const deleteAllCookies = () => {
const cookies = document.cookie.split(";");
for (const cookie of cookies) {
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";
}
}
deleteAllCookies()
We create the deleteAllCookies
function that splits the document.cookie
string.
Then we loop through each cookie within the cookies
array.
And then we get the index of the =
sign and remove the equal sign if it’s not there.
Then we add the expires=Thu, 01 Jan 1970 00:00:00 GMT
string after it to remove the cookie by making it expire.
This won’t delete cookies with the HttpOnly
flag set since the flag disables JavaScript’s access to the cookie.
It also won’t delete cookies that have a Path
value set.
This is because we can’t delete it without specifying the same Path
value with which it’s set.
Conclusion
We can clear some cookies from the browser by splitting the cookie string and then adding an expiry date to it that’s earlier than the current date and time.