Contact Us
Email: info@mohitdesigns.com
Mobile: +91-9718991639
Contact Us
Email: info@mohitdesigns.com
Mobile: +91-9718991639
JavaScript cookies are tiny data files which are kept by the web browser on the user’s device. They are utilised to keep user data across multiple web pages and sessions.
Key-value pairs connected to a web domain are called cookies. They support managing login statuses, storing preferences, and tracking user sessions.
To create a cookie, use the document.cookie
property:
document.cookie = "username=MohitSoni; expires=Fri, 29 May 2024 22:51:51 GMT; path=/";
username=MohitSoni
: Key-value pair.expires
: Expiration date (this is optional).path
: URL path where the cookie is accessible (this is optional).To read cookies, access document.cookie
. It returns all cookies in a single string:
let cookies = document.cookie;
console.log(cookies);
For individual cookies, parse the string:
function getCookie(name) {
let cookieArray = document.cookie.split(";");
for(let i = 0; i < cookieArray.length; i++) {
let cookiePair = cookieArray[i].split("=");
if(name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}
let username = getCookie("username");
console.log(username);
To update a cookie, we can set it again with the same data. Like name but new value and properties:
document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";
To delete a cookie, you can set its expiration date to a past date:
document.cookie = "username=; expires=Thu, 01 Jan 1975 11:00:00 GMT; path=/";
HttpOnly
: Ensures that the cookie is accessible only through HTTP(S) and not JavaScript.Secure
: Ensures that the cookie is sent only over HTTPS protocol.document.cookie = "username=MohitSoni; expires=Fri, 30 Dec 2024 23:00:59 GMT; path=/; Secure; HttpOnly";
Here’s a practical real world example to remember a user’s theme preference using cookie:
function setSiteTheme(theme) {
document.cookie = `theme=${theme}; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/`;
document.body.className = theme;
}
function applySiteThemeFromCookie() {
let theme = getCookie("theme");
if (theme) {
document.body.className = theme;
}
}
applySiteThemeFromCookie();
This script sets a theme cookie in the browser and applies it on when page loads.
Cookies set by JavaScript are necessary to save online preferences and states. You can improve the user experience on your website by knowing how to set up, read, update, and remove cookies. Always manage cookies safely to safeguard user information.