This article explains the use of cookies in JavaScript. We know that HTTP is a stateless protocol, in other words, each and every request to the webserver is new. It does not remember any previous history of requests. So, to maintain persistence between requests we can use various techniques. They are called state management techniques.
Cookies are data, stored in small text files, on your computer.
When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.
Cookies were invented to solve the problem "how to remember information about the user":
- When a user visits a web page, his name can be stored in a cookie.
- Next time the user visits the page, the cookie "remembers" his name.
Cookies are two types in nature
Persistence cookies: This type of cookies remain active even after the browser window is closed. There is a certain time limitation for them, it might be a few days or a few years.
Non-persistence cookies: This type of cooky is deleted automatically after the browser closes.
Create cookie in JavaScript
In this example, we will create one simple cookie. Have a look at the following example.
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- </head>
- <body>
- <script>
- document.cookie = "name=" + 'Sourav Kayal';
- console.log(document.cookie.split(';'));
- </script>
- </body>
- </html>
Show all cookies
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- </head>
- <body>
- <script>
- console.log("Name of cookies:- " + document.cookie);
- </script>
- </body>
- </html>
Show all cookies with key value pair
This is another way to show all the cookies. In this example we will print all the cookies with key-value pair. At first, we will extract all cookies from the document object and then we will go through all of them using a for a loop.
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- </head>
- <body>
- <script>
-
-
- var cookies = document.cookie;
-
-
- ArrayCook = cookies.split(';');
-
-
- for (var i = 0; i < ArrayCook.length; i++) {
- name = cookiearray[i].split('=')[0];
- value = cookiearray[i].split('=')[1];
- console.log("Key is : " + name + " and Value is : " + value);
- }
-
- </script>
- </body>
- </html>
Set persistent cookie
We can create a persistent cookie by specifying an expires property for the cookie. In this example we are creating one cookie that will stay in the computer for 1 month. Have a look at the following code.
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- </head>
- <body>
- <script>
-
- var today = new Date();
- today.setMonth(today.getMonth() + 1);
- cookievalue = 'Rama Sagar';
- document.cookie = "name=" + cookievalue;
- document.cookie = "expires=" + today.toUTCString() + ";"
- console.log("Cookie set : " + "name=" + cookievalue);
-
- </script>
- </body>
- </html>
Summary
This article explained cookies in JavaScript.