JavaScript Cookies
JavaScript Cookies are small text files that are stored on a user's computer by a web browser.
They are commonly used to store information about the user or their browsing activity, such as login credentials, preferences, shopping cart items, and tracking information.
When a user visits a website, the web server can send a cookie to the user's browser to be stored on their computer.
The cookie is then sent back to the server with every subsequent request from the same browser, allowing the server to identify the user and provide personalized content or services.
Here are some key points about cookies:
- Cookies are small text files that are stored on a user's computer by a web browser.
- They are commonly used to store information about the user or their browsing activity, such as login credentials, preferences, shopping cart items, and tracking information.
- When a user visits a website, the web server can send a cookie to the user's browser to be stored on their computer.
- The cookie is then sent back to the server with every subsequent request from the same browser, allowing the server to identify the user and provide personalized content or services.
- Cookies can be created and managed in JavaScript using the
document.cookie
property. You can set, get, and delete cookies using this property and manipulate their values and expiration dates.
Create a Cookie using JavaScript
To create a cookie with JavaScript, you can set the document.cookie
property to a string that contains the cookie name, value, and any additional options such as the expiration date or the path and domain for which the cookie is valid.
Here's an example that creates a cookie named "username" with a value of "John Doe" that expires in 7 days:
const now = new Date();
const expiryDate = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000); // 7 days from now
document.cookie =
"username=John Doe; expires=" + expiryDate.toUTCString() + "; path=/";
In this example:
- We first create a
Date
object for the current time usingnew Date()
. - We then create another Date object for the expiration date, which is 7 days from now, by adding 7 days' worth of milliseconds to the current time using
now.getTime() + 7 * 24 * 60 * 60 * 1000
. - We then set the
document.cookie
property to a string that contains the cookie name and value separated by an equal sign, followed by the expires option and the expiration date in UTC format usingtoUTCString()
, and the path option to specify the path for which the cookie is valid.
Read a Cookie using JavaScript
You can read a cookie by accessing the document.cookie
property. The document.cookie
property contains a string that represents all the cookies associated with the current document. You can parse this string to extract individual cookies.
Here's an example of how you can read a cookie using JavaScript:
// Function to get the value of a cookie by its name
function getCookie(cookieName) {
const cookies = document.cookie.split(";"); // Split the cookies string into an array
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim(); // Remove leading and trailing spaces
if (cookie.startsWith(cookieName + "=")) {
// Check if the cookie name matches
return cookie.substring(cookieName.length + 1); // Return the cookie value
}
}
return null; // Return null if cookie not found
}
// Usage example
const myCookieValue = getCookie("myCookie"); // Replace "myCookie" with your cookie name
if (myCookieValue) {
console.log("Cookie value:", myCookieValue);
} else {
console.log("Cookie not found");
}
In this example:
- The
getCookie()
function takes a cookie name as an argument and searches for that cookie in thedocument.cookie
string. - If the cookie is found, it returns the cookie value; otherwise, it returns
null
. - You can replace
"myCookie"
with the name of the cookie that you want to read.
Change a Cookie using JavaScript
To change a cookie, you simply need to set a new value for the cookie with the same name as the existing cookie.
Here's an example of how you can change a cookie using JavaScript:
// Function to set a new value for a cookie
function setCookie(cookieName, cookieValue, expirationDays) {
const date = new Date(); // Get current date
date.setTime(date.getTime() + expirationDays * 24 * 60 * 60 * 1000); // Set expiration date
const expires = "expires=" + date.toUTCString(); // Format expiration date string
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/"; // Set cookie with new value
}
// Usage example
setCookie("myCookie", "new value", 7); // Replace "myCookie" with your cookie name, "new value" with the new value you want to set, and 7 with the number of days until the cookie expires.
In this example:
- The
setCookie()
function takes three arguments: the name of the cookie, the new value for the cookie, and the number of days until the cookie expires. - It sets the new value for the cookie and updates the expiration date.
- You can replace
"myCookie"
with the name of the cookie that you want to change,"new value"
with the new value that you want to set, and7
with the number of days until the cookie should expire.
Note that you must set the expiration date in the future.
Delete a Cookie using JavaScript
You can delete a cookie using JavaScript by setting its expiration date to a past date. When the expiration date of a cookie is in the past, the browser automatically deletes the cookie.
Here's an example of how you can delete a cookie using JavaScript:
// Function to delete a cookie by name
function deleteCookie(cookieName) {
document.cookie = cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
// Usage example
deleteCookie("myCookie"); // Replace "myCookie" with your cookie name
In this example
- The
deleteCookie()
function takes the name of the cookie as an argument and sets its expiration date to a past date. - The
expires
attribute is set to Thu, 01 Jan 1970 00:00:00 UTC, which is a past date. - When the browser sees this expiration date, it deletes the cookie.
- You can replace
"myCookie"
with the name of the cookie that you want to delete.
The path
attribute must be set to the same path that was used to set the cookie in order to delete it.