Tuesday, May 5, 2020

JavaScript Cookies

JavaScript Cookies

Cookies enable us to store user data on web pages.


A cookie is a data stored in small text files in our browser.

The HTTP protocol is a stateless protocol; it means every request to the webserver is a new request. So, when a web server has sent a response back to the browser, the connection is closed, and the server forgets everything about this user interaction (no session information is recorded).

Cookies help us to maintain session information among different pages.

We can store the information about the user using the cookies as text data in name-value pairs.

Cookies provide a way of tracking user preferences, purchases, commissions, and other information. We can use them to provide better user experience or site statistics.

How Does Cookie Work?

  • First, a server sends some data to the user’s browser in the form of a cookie.
  • If the browser accepts the cookies, then the data will be stored as plain text.
  • Next time, when the visitor comes to the web page again, the cookie "remembers" the data associated with the visitor.

A cookie is a property of a document object. We can read/write the cookies associated with the document.

Basically, Cookies are a plain text containing name=value pairs. A cookie can also have following fields

  • Expires – This is the date when the cookie will be expired. If it is not specified, the cookie will expire when the visitor exits the browser.
  • Domain − This is the domain name of the site.
  • Name=Value, it used to set the cookie value
  • Path − This represents the path to the directory or web page that sets the cookie.
  • Secure – This field represents that if this filed is set then the cookie can be retrieved with a secure server only.

Creating cookies with JavaScript

We can write a new cookie as,

document.cookie = newCookie;

We can set a simple cookie having name=value as,

document.cookie = "username=Iron Man";

other fields like path, domain, etc. can also be added to the cookie by simply separating them with a semi-colon (;)

document.cookie = "username=Iorn Man; expires=Thu, 20 Dec 2020 12:00:00 UTC; path=/";

For example,

  document.cookie = "userName=Iron Man";
  document.cookie = "userEmail=ironamn@starkind.org";
  function showCookies() {
  <body bgcolor='yellow'>
    <button onclick='showCookies()'>click</button>

userName=Iron Man; userEmail=ironamn@starkind.org

Reading the cookies

Reading the cookies is as simple as writing the cookies. To get all the cookies associated with a document object, we can use

allCookies = document.cookie;

Here, allCookies is a string containing semicolon-separated list all the cookies associated with the document object.

<title>cookie Demo</title>
      <script type = "text/javascript">
            function getAllCookies() {
               var allcookies = document.cookie;
               document.write ("All Cookies : " + allcookies );
               // Get all the cookies pairs in an array
               cookie_arr = allcookies.split(';');
               // Now take key value pair out of this array
               for(var i=0; i<cookie_arr.length; i++) {
                  name = cookie_arr[i].split('=')[0];
                  value = cookie_arr[i].split('=')[1];
                  document.write ("Key is : " + name + " and Value is : " + value+"<br>");
   <body bgcolor="yellow">     
         <p> All cookies list</p>
         <button onclick = "getAllCookies()">show cookies</button>     

All Cookies : userName=Iron Man; userEmail=IronMan@StarkCorp.orgKey is : userName and Value is : Iron Man
Key is : userEmail and Value is : IronMan@StarkCorp.org

Updating(overwriting) Cookies

We can overwrite a cookie using the same way we create a cookie.

document.cookie = "username=Super Man; expires=Fri, Dec 20 12:00:00 UTC; path=/";

Delete a Cookie with JavaScript

Deleting a cookie is very easy. We just need to overwrite the cookie with no value and set the expires parameter to a passed date to delete a cookie.

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; 

We also need to specify the cookie path to make sure that the deleted cookie is the right cookie.