Home  >  Article  >  Web Front-end  >  How to Delete All Cookies Programmatically with JavaScript?

How to Delete All Cookies Programmatically with JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-25 10:33:11619browse

How to Delete All Cookies Programmatically with JavaScript?

Deleting All Cookies with JavaScript

Question: How can I programmatically remove all cookies for the current domain using JavaScript?

Answer: JavaScript provides a method to delete all cookies stored by the browser for the current domain. Here's a function that accomplishes this:

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';
    });
}

However, there are limitations associated with this technique:

  • HttpOnly Cookies: It cannot delete cookies marked as HttpOnly, which JavaScript is prohibited from accessing.
  • Path-Specific Cookies: It also fails to remove cookies with a specific Path value. JavaScript can only delete cookies with matching paths.

By calling the deleteAllCookies() function, you can effectively clear all non-HttpOnly cookies for the current domain without specifying paths.

The above is the detailed content of How to Delete All Cookies Programmatically with 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