Home >Web Front-end >JS Tutorial >How Can I Delete All Cookies Using JavaScript?

How Can I Delete All Cookies Using JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 08:44:101001browse

How Can I Delete All Cookies Using JavaScript?

Purging Cookies with JavaScript

In the realm of web development, the ability to manage cookies is pivotal. JavaScript, a versatile web scripting language, provides a powerful mechanism to remove all cookies associated with the current domain.

Solution

The JavaScript code below efficiently deletes every cookie within the current domain:

function deleteAllCookies() {
    // Split the cookie string into an array of individual cookies
    document.cookie.split(';').forEach(cookie => {
        // Determine the name of the cookie
        const eqPos = cookie.indexOf('=');
        const name = eqPos > -1 ? cookie.substring(0, eqPos) : cookie;
        // Expire the cookie into oblivion
        document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT';
    });
}

Limitations

While this solution is effective in most scenarios, it's important to be aware of its limitations:

  1. HttpOnly Flag: Cookies with the HttpOnly flag are inaccessible to JavaScript, so they cannot be deleted using this method.
  2. Path Value: Cookies with a Path value can only be deleted if the Path value is explicitly specified in the code. Otherwise, these cookies will remain intact.

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

Statement:
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