JS Cookies
Web browsers and web servers use HTTP to communicate with each other. But, HTTP is a stateless protocol. However, for a e-Commerce website to work, we need to maintain conversational state (i.e. session) information among different web pages. For example, one user completes registration process after visiting many pages. That is why we have to maintain users’ session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, and other information required for better visitor experience or web site statistics.
Cookies are basically data, stored in small text files, on our computer or notebook.
Cookies are saved in name-value pairs like:
name=Virat Kohli
When a web browser requests a web page from a server, cookies which are part of the page are added to the request. This way the web server retrieves the necessary data to recall information about users.
In JS, a cookie can be created like this:
document.cookie = "name=Virat Kohli";
Creating and Retrieving Cookies
In JS, we can create, retrieve, update and delete a cookie by using document.cookie property. See the example code below.
Cookie Example.
<html>
<head>
</head>
<body>
<center>
<input type="button" value="Create Cookie" onclick="createCookie()">
<input type="button" value="Retrieve Cookie" onclick="retrieveCookie()">
</center>
<script>
function createCookie() {
document.cookie = "name=Virat Kohli";
}
function retrieveCookie() {
if(document.cookie.length!=0) {
alert(document.cookie);
}
else {
alert("Cookie is not available");
}
}
</script>
</body>
</html>
Cookie Attributes
JS provides some optional attributes that enhance the functionality of cookies. Here comes the list of some attributes with their description.
Attributes | Description |
---|---|
expires | It maintains the state of a cookie up to the specified date and time. |
max-age | It maintains the state of a cookie up to the specified time. Here, time is given in seconds. |
path | It expands the scope of the cookie to all the pages of a website. |
domain | It is used to specify the domain for which the cookie is valid. |
Cookie expires attribute
Deleting a cookie is very easy. We don’t have to specify a cookie value for deleting a cookie. We have to set the expires attribute to a passed date:
The cookie expires attribute provides one of the ways to create a persistent cookie. Here, a date and time are declared that represents the active period of a cookie. Once the declared time is passed, a cookie is deleted automatically.
Let’s see a code snippet of cookie expires attribute.
function createCookie() {
var d = new Date();
d.setTime(d.getTime() + (60 * 60 * 24 * 365));
var expires = "expires="+ d.toUTCString();
document.cookie = "name=Virat Kohli" + ";" + expires + ";path=/";
}