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);
document.cookie =
"username=John Doe; expires=" + expiryDate.toUTCString() + "; path=/";
In this example:
- We first create a
Date
object for the current time using new 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 using toUTCString()
, 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 getCookie(cookieName) {
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.startsWith(cookieName + "=")) {
return cookie.substring(cookieName.length + 1);
}
}
return null;
}
const myCookieValue = getCookie("myCookie");
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 the document.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 setCookie(cookieName, cookieValue, expirationDays) {
const date = new Date();
date.setTime(date.getTime() + expirationDays * 24 * 60 * 60 * 1000);
const expires = "expires=" + date.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/";
}
setCookie("myCookie", "new value", 7);
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, and 7
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 deleteCookie(cookieName) {
document.cookie = cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
deleteCookie("myCookie");
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.