Home > Web Front-end > JS Tutorial > How to Delete All Cookies for the Current Domain Using JavaScript?

How to Delete All Cookies for the Current Domain Using JavaScript?

Susan Sarandon
Release: 2024-11-27 04:33:15
Original
339 people have browsed it

How to Delete All Cookies for the Current Domain Using JavaScript?

Deleting All Cookies for Current Domain with JavaScript

In JavaScript, deleting all cookies for the current domain involves programmatically removing them from the browser's storage.

How to Delete All Cookies Using JavaScript

To clear all cookies for the current domain, you can use the following JavaScript function:

function deleteAllCookies() {
    document.cookie.split(';').forEach(cookie => {
        const eqPos = cookie.indexOf('=');
        const name = eqPos > -1 ? cookie.substring(0, eqPos) : cookie;
        document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT';
    });
}
Copy after login

This function iterates through all cookies stored in the document's cookie property, extracting their names and setting them with an expiration date in the past (January 1, 1970), effectively "deleting" them.

Limitations of the Approach

Note that this code has some limitations:

  • It cannot delete cookies with the HttpOnly flag set, which prevents JavaScript from accessing them.
  • It cannot delete cookies set with a specific Path value and requires matching the Path value used when setting the cookie.

The above is the detailed content of How to Delete All Cookies for the Current Domain Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template