Home > Web Front-end > JS Tutorial > How Can JavaScript Delete All Cookies from the Current Domain?

How Can JavaScript Delete All Cookies from the Current Domain?

DDD
Release: 2024-11-25 13:56:15
Original
724 people have browsed it

How Can JavaScript Delete All Cookies from the Current Domain?

Purging Cookies with JavaScript

When navigating the vast digital realm, cookies serve as tiny data packets that websites store on your computer or device. They aid in remembering your browsing preferences and enhancing your user experience. However, at times, you may wish to clear all cookies for a specific domain, perhaps due to privacy concerns or troubleshooting purposes.

JavaScript-Powered Cookie Clearing

To obliterate all cookies associated with the current domain using JavaScript, you can employ the following code:

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 code effectively loops through each cookie stored in the document.cookie property, using the ; character as a separator. For each cookie, it extracts the cookie name and overwrites it with an expiration date set in the distant past. By doing so, the cookies are effectively purged from your system.

Caveats to Consider

While this code is generally effective, it's essential to be aware of the following limitations:

  • HttpOnly Flag: If a cookie has the HttpOnly flag set, JavaScript will be unable to access and delete it.
  • Path Value: Cookies with a specified Path value cannot be deleted unless the same Path value is provided in the deletion code.

The above is the detailed content of How Can JavaScript Delete All Cookies from the Current Domain?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template