JS Deleting Cookies

In JavaScript, cookies can be deleted using several methods. Here are the different ways to delete a cookie:

Using the expires Attribute: Setting the expires attribute to a past date.

Using the max-age Attribute: Setting the max-age attribute to 0.

Deleting Cookies via the Web Browser: Manually deleting cookies through browser settings.

1. Using the expires Attribute

To delete a cookie, you can set its expires attribute to a past date. This method is supported by all browsers.

Example:

// Set a cookie
document.cookie = "username=JohnDoe; path=/; expires=Fri, 31 Dec 2024 23:59:59 GMT";

// Delete the cookie by setting expires to a past date
document.cookie = "username=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";

2. Using the max-age Attribute

The max-age attribute specifies the maximum age of the cookie in seconds. To delete a cookie, set max-age to 0.

Example:

// Set a cookie
document.cookie = "username=JohnDoe; path=/; max-age=3600"; // 1 hour

// Delete the cookie by setting max-age to 0
document.cookie = "username=; path=/; max-age=0";

3. Deleting Cookies via the Web Browser

You can also delete cookies manually through the web browser settings. This process varies depending on the browser being used:

Chrome: Go to Settings > Privacy and security > Cookies and other site data > See all cookies and site data.

Firefox: Go to Preferences > Privacy & Security > Cookies and Site Data > Manage Data.

Safari: Go to Preferences > Privacy > Manage Website Data.

Example for deleting cookie:

<script>
    // Function to set a cookie
    function setCookie(name, value, days) {
        let expires = "";
        if (days) {
            let date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }

    // Function to delete a cookie by setting expires attribute to a past date
    function deleteCookieByExpires(name) {
        document.cookie = name + "=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }

    // Function to delete a cookie by setting max-age attribute to 0
    function deleteCookieByMaxAge(name) {
        document.cookie = name + "=; path=/; max-age=0";
    }

    // Set and delete cookie examples
    function example() {
        // Set a cookie
        setCookie("username", "JohnDoe", 7);

        // Delete the cookie using expires attribute
        deleteCookieByExpires("username");

        // Set a cookie again
        setCookie("username", "JohnDoe", 7);

        // Delete the cookie using max-age attribute
        deleteCookieByMaxAge("username");
    }
</script>