1. Test if cookies are enabled
If you want to check whether cookies are enabled before using them, you can use navigator.cookieEnabled:
if (navigator.cookieEnabled === false)
{
alert("Warning: Cookies are not enabled in your browser!");
}
Note that on older browsers
navigator.cookieEnabledmay not exist, so in that case you won't detect that cookies are not enabled.
2. Adding and Setting Cookies
Cookies are saved in name-value pairs : username = Jack
To simply create a cookie you can use document.cookie property
You can also add an expiry date (in UTC time) and a path parameter, you can tell the browser what path the cookie belongs to.
Here is an example setup:
// Define cookie properties
const COOKIE_NAME = "ExampleCookie"; // The cookie's name
const COOKIE_VALUE = "Hello, Cookie!"; // The cookie's value
const COOKIE_PATH = "/example/jack"; // The cookie's path
// Calculate the expiration time (1 minute in the future)
const expirationTime = new Date(Date.now() + 60000); // 60000ms = 1 minute
// Format expiration time to UTC string
const COOKIE_EXPIRES = expirationTime.toUTCString();
// Set the cookie with the defined properties
document.cookie = `${COOKIE_NAME}=${COOKIE_VALUE}; expires=${COOKIE_EXPIRES}; path=${COOKIE_PATH}`;
3. Reading Cookies
To read cookies document.cookie property will return all cookies in one string like: cookie1=value; cookie2=value; cookie3=value;
4. Removing Cookies
To remove a cookie, you don't have to specify a cookie value. Just set the expires parameter to a past date:
document.cookie = `${COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${COOKIE_PATH};`;
If you found this useful, consider:
✅ Follow @iarchitsharma for more content like this
✅ Follow me on Twitter
Top comments (0)