To set a cookie in JavaScript, you can use the setCookie
function:
function setCookie(name, value, expires, path, domain, secure) {
var cookie = name + "=" + encodeURIComponent(value);
if (expires) {
cookie += "; expires=" + expires.toGMTString();
}
if (path) {
cookie += "; path=" + path;
}
if (domain) {
cookie += "; domain=" + domain;
}
if (secure) {
cookie += "; secure";
}
document.cookie = cookie;
}
This function takes the following parameters:
name
: the name of the cookievalue
: the value to store in the cookieexpires
: aDate
object that specifies when the cookie should expirepath
: the path on the server to which the cookie should be sentdomain
: the domain that the cookie should be sent tosecure
: a boolean value that specifies whether the cookie should only be sent over a secure connection (HTTPS)
To use this function, you can call it with the appropriate arguments:
setCookie("username", "John", new Date("January 1, 2025"), "/", "example.com", true);
This will set a cookie with the name “username” and the value “John”, that expires on January 1, 2025, is sent to the root path on the server, is sent to the “example.com” domain, and is only sent over a secure connection.
To unset a cookie, you can set it to expire in the past. For example:
setCookie("username", "", new Date(0), "/", "example.com", true);
This will set the “username” cookie to an empty string, with an expiration date in the past, effectively deleting the cookie.
Alternatively, you can use the removeCookie
function:
function removeCookie(name) {
setCookie(name, "", new Date(0), "/");
}
This function takes the name of the cookie as a parameter and sets the cookie to an empty string with an expiration date in the past, effectively deleting the cookie.
removeCookie("username");