The HTML Document cookie
Property: Managing Cookies in Web Pages
The HTML Document cookie
property allows JavaScript to read, create, modify, and delete cookies associated with the current web page. Cookies are small text files stored on the user’s computer, used for various purposes such as session management, personalization, and tracking user behavior. Understanding how to manipulate cookies via the document.cookie
property is essential for building interactive and personalized web applications.
What is the Document cookie
Property?
The document.cookie
property is a string that contains a semicolon-separated list of all cookies available to the current document. This property provides both read and write access to the cookies, enabling you to manage cookies effectively using JavaScript.
Purpose of the Document cookie
Property
The primary purposes of the document.cookie
property are:
- Read Cookies: Retrieve the values of existing cookies.
- Create Cookies: Set new cookies with specific names, values, and attributes.
- Modify Cookies: Update the values or attributes of existing cookies.
- Delete Cookies: Remove cookies by setting their expiration date to a past time.
Syntax and Attributes
Syntax
To access or modify cookies, use the following syntax:
let cookieString = document.cookie; // To read cookies
document.cookie = "cookieName=cookieValue; expires=date; path=path"; // To set cookies
Attributes
When setting a cookie, you can specify several attributes to control its behavior:
Attribute | Description |
---|---|
`cookieName=cookieValue` | The name and value of the cookie. |
`expires=date` | The expiration date of the cookie, after which the cookie will be automatically deleted. The date should be in the format `Wdy, DD Mon YYYY HH:MM:SS GMT`. If not specified, the cookie becomes a session cookie and is deleted when the browser is closed. |
`max-age=seconds` | Specifies the number of seconds until the cookie expires. Cannot be used together with `expires`. |
`path=path` | Specifies the path for which the cookie is valid. If not specified, it defaults to the directory of the current page. Setting it to `/` makes the cookie available for the entire domain. |
`domain=domain` | Specifies the domain for which the cookie is valid. If not specified, it defaults to the domain of the current page. |
`secure` | Indicates that the cookie should only be transmitted over HTTPS. |
`samesite=strict|lax|none` | Controls whether the cookie is sent with cross-site requests.
|
Note: Cookies set without an expires
or max-age
attribute are considered session cookies and are deleted when the browser closes. ⏳
Examples of Using the Document cookie
Property
Let’s explore practical examples of how to use the document.cookie
property to manage cookies in web applications.
Reading Cookies
To read all cookies, simply access the document.cookie
property. Since it returns a string of semicolon-separated values, you’ll typically need to parse the string to extract individual cookie values.
<!DOCTYPE html>
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<p id="cookieDisplay"></p>
<script>
const cookieDisplayElement = document.getElementById('cookieDisplay');
const allCookies = document.cookie;
if (allCookies === "") {
cookieDisplayElement.textContent = "No cookies found.";
} else {
cookieDisplayElement.textContent = "All Cookies: " + allCookies;
}
</script>
</body>
</html>
This code reads all the cookies and displays them in a paragraph. If there are no cookies, it displays “No cookies found.”
Setting a Cookie
To set a cookie, assign a string with the cookie’s name, value, and attributes to the document.cookie
property.
<!DOCTYPE html>
<html>
<head>
<title>Setting a Cookie</title>
</head>
<body>
<button id="setCookieButton">Set Cookie</button>
<script>
const setCookieButton = document.getElementById('setCookieButton');
setCookieButton.addEventListener('click', function() {
document.cookie = "username=JohnDoe; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/";
alert("Cookie has been set!");
});
</script>
</body>
</html>
Clicking the “Set Cookie” button sets a cookie named username
with the value JohnDoe
, an expiration date, and a path.
Getting a Specific Cookie Value
To get the value of a specific cookie, you can use a function to parse the document.cookie
string and return the value associated with the cookie name.
<!DOCTYPE html>
<html>
<head>
<title>Getting a Specific Cookie Value</title>
</head>
<body>
<p id="cookieValueDisplay"></p>
<script>
function getCookie(name) {
const cookieString = document.cookie;
const cookies = cookieString.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.startsWith(name + '=')) {
return cookie.substring(name.length + 1);
}
}
return "";
}
const cookieValueDisplayElement = document.getElementById('cookieValueDisplay');
const username = getCookie("username");
if (username !== "") {
cookieValueDisplayElement.textContent = "Username: " + username;
} else {
cookieValueDisplayElement.textContent = "Username cookie not found.";
}
</script>
</body>
</html>
This code defines a getCookie
function that parses the document.cookie
string to find and return the value of the specified cookie.
Deleting a Cookie
To delete a cookie, set its expiration date to a past time. This will cause the browser to remove the cookie.
<!DOCTYPE html>
<html>
<head>
<title>Deleting a Cookie</title>
</head>
<body>
<button id="deleteCookieButton">Delete Cookie</button>
<script>
const deleteCookieButton = document.getElementById('deleteCookieButton');
deleteCookieButton.addEventListener('click', function() {
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
alert("Cookie has been deleted!");
});
</script>
</body>
</html>
Clicking the “Delete Cookie” button sets the username
cookie’s expiration date to a past time, effectively deleting it.
Using secure
and samesite
Attributes
To enhance cookie security, use the secure
and samesite
attributes. The secure
attribute ensures that the cookie is only transmitted over HTTPS, while the samesite
attribute controls whether the cookie is sent with cross-site requests.
<!DOCTYPE html>
<html>
<head>
<title>Secure Cookie Example</title>
</head>
<body>
<button id="setSecureCookieButton">Set Secure Cookie</button>
<script>
const setSecureCookieButton = document.getElementById('setSecureCookieButton');
setSecureCookieButton.addEventListener('click', function() {
document.cookie = "sessionID=12345; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/; secure; samesite=strict";
alert("Secure cookie has been set!");
});
</script>
</body>
</html>
This example sets a secure cookie named sessionID
that is only transmitted over HTTPS and with same-site requests.
Real-World Applications of the Document cookie
Property
The Document cookie
property is used in various web development scenarios, including:
- Session Management: Maintaining user session information across multiple pages.
- Personalization: Storing user preferences and settings for a personalized experience.
- Tracking User Behavior: Monitoring user activity and collecting data for analytics.
- Authentication: Storing authentication tokens to verify user identity.
- Remember Me Functionality: Remembering user login credentials for future visits.
Use Case Example: Implementing a “Remember Me” Feature
Let’s create a practical example that demonstrates how to use the document.cookie
property to implement a “Remember Me” feature on a login form.
<!DOCTYPE html>
<html>
<head>
<title>Remember Me Example</title>
</head>
<body>
<form id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="checkbox" id="rememberMe" name="rememberMe">
<label for="rememberMe">Remember Me</label><br><br>
<button type="submit">Login</button>
</form>
<script>
const loginForm = document.getElementById('loginForm');
// Function to set a cookie
function setCookie(name, value, days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
// Function to get a cookie
function getCookie(name) {
const cookieName = name + "=";
const decodedCookie = decodeURIComponent(document.cookie);
const cookieArray = decodedCookie.split(';');
for(let i = 0; i < cookieArray.length; i++) {
let cookie = cookieArray[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1);
}
if (cookie.indexOf(cookieName) === 0) {
return cookie.substring(cookieName.length, cookie.length);
}
}
return "";
}
// Function to handle form submission
loginForm.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent the form from submitting
const usernameInput = document.getElementById('username');
const rememberMeCheckbox = document.getElementById('rememberMe');
if (rememberMeCheckbox.checked) {
setCookie("rememberedUsername", usernameInput.value, 30); // Remember for 30 days
alert("Username remembered for 30 days!");
} else {
document.cookie = "rememberedUsername=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; // Delete the cookie
alert("Username not remembered.");
}
});
// Check if the username is already remembered
window.onload = function() {
const usernameInput = document.getElementById('username');
const rememberedUsername = getCookie("rememberedUsername");
if (rememberedUsername !== "") {
usernameInput.value = rememberedUsername;
}
};
</script>
</body>
</html>
This example demonstrates several important concepts:
- Setting Cookies: When the “Remember Me” checkbox is checked, a cookie containing the username is set with an expiration date of 30 days.
- Reading Cookies: On page load, the script checks for the “rememberedUsername” cookie and populates the username input field if the cookie is found.
- Deleting Cookies: If the “Remember Me” checkbox is not checked, the script deletes the cookie by setting its expiration date to a past time.
- Functions for Cookie Management: The
setCookie
andgetCookie
functions encapsulate the logic for setting and retrieving cookies, making the code more modular and readable.
This is a simplified example, and in a real-world scenario, you would also handle the password securely (e.g., by storing a hash of the password in a secure cookie or using server-side session management). However, this example effectively demonstrates how to use the document.cookie
property to implement a “Remember Me” feature.
Browser Support
The Document cookie
property enjoys excellent support across all modern web browsers, ensuring that your web applications can manage cookies consistently across different platforms.
Note: Always test your cookie management code across different browsers and devices to ensure a consistent user experience and to handle any browser-specific quirks. 🧐
Security Considerations
When working with cookies, it’s essential to be aware of potential security risks:
- Cross-Site Scripting (XSS): Protect against XSS attacks by sanitizing cookie values and avoiding storing sensitive information in cookies.
- Cross-Site Request Forgery (CSRF): Use anti-CSRF tokens to prevent unauthorized requests.
- Secure Attribute: Always use the
secure
attribute for cookies that contain sensitive information to ensure they are only transmitted over HTTPS. - HttpOnly Attribute: Consider using the
HttpOnly
attribute (set server-side) to prevent client-side scripts from accessing the cookie, further mitigating XSS risks. - SameSite Attribute: Use the
SameSite
attribute to control whether cookies are sent with cross-site requests, providing additional protection against CSRF attacks.
Conclusion
The HTML Document cookie
property is a fundamental tool for managing cookies in web applications. By understanding how to read, create, modify, and delete cookies, you can build interactive and personalized user experiences. Remember to follow security best practices to protect against potential risks and ensure the privacy of your users. Happy coding!