What are Cookies?
A cookie is a small data file that your browser saves on your computer, allowing it to be accessed later. You might have experienced the advantages of cookies, whether you’re aware of it or not. For instance, have you ever opted to save your Facebook password so you don’t need to type it each time you log in? If so, you’re actually utilizing cookies. These cookies are stored as key/value pairs, enabling your browser to remember certain information for improved user experience.
Why do you need a Cookie?
Cookies are used to store small pieces of data on a user’s web browser. They serve various purposes and are commonly utilized for the following reasons:
- Session Management: Cookies are often used to manage user sessions on websites. When you log in to a website, a session cookie is created, allowing the server to recognize you as the same user during your visit. This helps maintain your logged-in state across different pages on the website.
- Personalization: Cookies can store user preferences and settings, enabling websites to personalize the user experience. For instance, a website might remember your language preference or theme choice through cookies.
- Tracking and Analytics: Cookies are employed to track user behavior on websites. This data is valuable for website owners to understand user interactions, improve website usability, and gather analytics for better decision-making.
- Shopping Carts and E-commerce: Cookies are used to maintain the contents of a user’s shopping cart during an online shopping session. This ensures that items remain in the cart even if the user navigates to different pages.
- Remembering User Information: Cookies can remember user details, such as usernames and passwords, to facilitate automatic login for returning users.
JavaScript cookies are a convenient and lightweight method to store data on the client side without requiring server-side scripting. The “document. cookie” property is commonly used to generate, read, edit, and delete cookies in JavaScript, making it easy to manage small amounts of data within the user’s browser. However, it’s important to note that cookies have limitations in terms of storage capacity and security, and their use should be balanced with considerations for user privacy and data protection.
Set-Cookie with Javascript
you can use the document.cookie
property to create a cookie using JavaScript.
2 3 4 |
document.cookie = "cookie_name=cookie_value" |
By default, when you create a cookie without specifying an expiry date, it becomes a “session cookie.” Session cookies are temporary and are stored only for the duration of the user’s browsing session. Once the user closes the browser, these cookies are automatically deleted.
On the other hand, if you want the cookie to persist beyond the current session, you can set an expiry date for the cookie. The expiry date is specified in UTC/GMT format and determines when the cookie should be deleted from the user’s computer.
When you set an expiry date for the cookie, it becomes a “persistent cookie.” Persistent cookies remain on the user’s computer even after they close the browser, and they will persist until the specified expiry date is reached.
To create a persistent cookie in JavaScript, you can use the “document.cookie” property and set the “expires” attribute to the desired date in UTC/GMT format. For example:
2 3 4 |
document.cookie = "name=tutorialswebsite; expires=Wed, 13 Jan 2021 12:00:00 UTC"; |
By setting the “expires” attribute, the cookie will be removed from the user’s computer on the specified date, even if they close and reopen the browser before that date. You can also specify the domain and path attributes to control which domain and directories the cookie belongs to. This allows you to manage the scope and accessibility of the cookie.
2 3 4 5 6 7 8 |
const expiryDate = new Date('2023-12-31T12:00:00Z').toUTCString(); const domain = "tutorialswebsite.com"; const path = "/products"; document.cookie = `myCookie=myValue; expires=${expiryDate}; domain=${domain}; path=${path}`; |
With the above code, the cookie “myCookie” will be associated with the domain “example.com” and will only be accessible on pages within the “/products” directory of that domain.
Read or Get Cookie with JavaScript
You can access the cookie and retrieved using the document.cookie property.
2 3 4 |
var value = document.cookie; |
Delete Cookie using JavaScript
To delete a cookie, you only need to set the value of the cookie to empty and set the value of the cookie to expire on the passed date.
2 3 4 |
document.cookie = "cookiename= ; expires = Thu, 01 Jan 1970 00:00:00 GMT" |
Change Cookie Value with JavaScript
Cookie value can be changed in the same way it created.
2 3 4 |
document.cookie = "name=Tutorialswebsite; expires=Wed, 13 Jan 2021 12:00:00 UTC; path=/"; |
Now, we’re going to build some custom functions to set, get, and delete cookies in JavaScript. These JavaScript functions can have a user-friendly way to use cookies on the web page.
Set-Cookie
The following setCookie()
function helps to create a cookie with a specific name and value using JavaScript.
- name – The name of the cookie.
- value – The value of the cookie.
- exp_days – The cookie expiry time in days.
2 3 4 5 6 7 8 9 |
function setCookie(name,value,exp_days) { var d = new Date(); d.setTime(d.getTime() + (exp_days*24*60*60*1000)); var expires = "expires=" + d.toGMTString(); document.cookie = name + "=" + value + ";" + expires + ";path=/"; } |
Note that: The “/” means that the cookie will be available in the entire website domain.
For Example:
2 3 4 5 6 |
setCookie("name", "Tutorialswebsite", 5); |
The above code is used to set a cookie named name
with the value Tutorialswebsite
for 5 days.
Get Cookie
getCookie()
the function helps to retrieve the value of a predefined cookie using JavaScript.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function getCookie(name) { var cname = name + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i < ca.length; i++){ var c = ca[i]; while(c.charAt(0) == ' '){ c = c.substring(1); } if(c.indexOf(cname) == 0){ return c.substring(cname.length, c.length); } } return ""; } |
For Example:
2 3 4 5 6 |
var user = getCookie("name"); |
The above code is used to get the value of the cookie name
.
Delete Cookie
The deleteCookie()
function helps to remove cookie using JavaScript.
2 3 4 5 6 7 8 9 10 11 |
function deleteCookie(name) { var d = new Date(); d.setTime(d.getTime() - (60*60*1000)); var expires = "expires=" + d.toGMTString(); document.cookie = name + "=;" + expires + ";path=/"; } |
For Example:
2 3 4 5 6 |
deleteCookie("name"); |
The above code is used to remove the cookie name
.
Try below Example code yourself
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<html> <head> <title>Tutorialswebsite get, set & delete Cookies</title> <script type="text/javascript"> function createTutorialswebsiteCookie(cookie_Name,cookie_Value,expireDays) { var date = new Date(); date.setTime(date.getTime()+(expireDays*24*60*60*1000)); document.cookie = cookie_Name + "=" + cookie_Value + "; expires=" + date.toGMTString(); } function accessMyCookie(cookie_Name) { var name = cookie_Name + "="; var allCookieArray = document.cookie.split(';'); for(var i=0; i<allCookieArray.length; i++) { var temp = allCookieArray[i].trim(); if (temp.indexOf(name)==0) return temp.substring(name.length,temp.length); } return ""; } function checkMyCookie() { var userVal = accessMyCookie("TutsCookie"); if (userVal!="") alert("Welcome Back " + userVal + "!!!"); else { userVal = prompt("Please enter your Cookies Name"); numVal = prompt("How many days your cookie will expire from your computer?"); if (userVal!="" && userVal!=null) { createTutorialswebsiteCookie("TutsCookie", userVal, numVal); } } } </script> </head> <body onload="checkMyCookie()"></body> </html> |
Conclusion
If you’d like to store cookie data on your website, the JavaScript cookie would be very useful. You can use these custom functions to handle JavaScript cookies. Well, I hope you found this tutorial helpful for your project. Keep learning!.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit a paid service request
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co