Home >Web Front-end >JS Tutorial >How Can I Create and Delete Cookies Using JavaScript?
Deletion of Cookies in JavaScript
You inquire about creating and deleting cookies using JavaScript. Here's an exploration of your code and a solution:
Your createCookie function incorporates the creation of a cookie, and the setCookie function sets a cookie with a specific name, value, and duration.
To address the deletion requirement, you can employ the eraseCookie function, which operates on the principle of creating a cookie with a name identical to the cookie you want to delete. However, you set its duration to a negative value (-1), essentially expiring it immediately, effectively removing the cookie from the browser.
Alternatively, you can utilize the delete_cookie() function, which accepts the cookie name as well as optional parameters for the path and domain associated with the cookie. It ensures that the specified cookie is deleted by setting its expiration date to a far-distant past time.
The following example illustrates the recommended approach:
function delete_cookie(name, path, domain) { const cookieExists = get_cookie(name); if (cookieExists) { document.cookie = `${name}=;path=${path || ""};domain=${domain || ""};expires=Thu, 01 Jan 1970 00:00:01 GMT`; } }
To determine if a cookie exists, you can define get_cookie() as follows:
function get_cookie(name) { const cookies = document.cookie.split(';'); return cookies.some((c) => c.trim().startsWith(`${name}=`)); }
By incorporating these functions, you can effectively manage cookies in your JavaScript programs, including their deletion.
The above is the detailed content of How Can I Create and Delete Cookies Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!