JavaScript Cookies

Cookie Basics :

A cookie (HTTP cookie) is a small piece of data sent from a website and stored in user's computer by the user's browser. They are designed to hold a modest amount of data specific to a particular client and website, and can be accessed either by the web server or the client computer. The users data like user name, email address, authentication details etc information are stored on the cookie.

When a web server has sent a web page to a browser, and the TCP connection is closed, then the serer forgets everything about the user. To solve this problem cookies are used, now when a browser requests a web page to a server, then the cookies belonging to that page or website will added to the request. This way the server gets the necessary information about users and provide them better user experience.

Cookies are stored on computers in key-value pairs. In HTTP communication , the Set-Cookie response header is used to set the cookies. For example :
  Set-Cookie: name=marry, expires=Mon, May 28 2018 15:00:00 GMT
The above statement will set the cookies with the name and expires filed, where the name field stores the username and the expires field stores the expiry date of the cookie. Some of the cookie attributes are as follows :

Name=Value : Cookies are set and retrieve in the form of key-value pairs.

Expires : The expires attribute set the expiry date/time for the cookie. If this field is blank, then the cookie will expire when the visitor quits the browser.

Domain : The domain attribute specifies those hosts to which the cookie will be sent.

Path : The path attribute Indicates a URL path that must exist in the requested resource before sending the Cookie header.

secure : A secure attribute specifies that the cookie will only be sent to the server when a request is made using SSL and the HTTPS protocol.

HttpOnly : The cookie with HTTPOnly attribute are not accessible to JavaScript's document.cookie API.


Handling Cookies with JavaScript :

In JavaScript we can create, read, delete cookies with the document.cookie property.

Creating Cookie with JavaScript :

The simplest way to create a cookie is to assign a string value to the document.cookie object.
 document.cookie = "key1=value1; key2=value2; expires=date";
Example :
 document.cookie="name=John; id=a45kwx; expires=Mon, May 28 2018 15:00:00 GMT";
Now lets see an example code :
<html>
<body>
  <input type="text" id="txtbox">
  <input type="button" onclick="setCookie()" value="Set Cookie"/>
  <input type="button" onclick="getCookie()" value="See Cookies"/> 
  <p id="demo1"></p>
  <script>
    function setCookie() {
      var data = document.getElementById('txtbox').value;
      var txtdata = document.getElementById('demo1');
      if(!Boolean(data)) {
        txtdata.innerText = "The box is empty.";
      } else {
        value = escape(data) + ";";
        document.cookie = "name=" + value;
        txtdata.innerText = "Cookie is setted.";
      }
    }

    function getCookie() {
      alert(document.cookie);
    }
  </script>
</body>
</html>
Output :

We can also add an expiry date for cookie, by default the cookie is deleted when the browser is closed. For example :
 document.cookie = "name=John Snow; expires=Mon, 28 May 2018 16:44:30 GMT;";
Example code :
<html>
<body>
  <input type="text" id="txtbox">
  <input type="button" onclick="setCookie()" value="Set Cookie"/>
  <input type="button" onclick="getCookie()" value="See Cookies"/> 
  <p id="demo1"></p>
  <script>
    
    function setCookie() {
      var data = document.getElementById('txtbox').value;
      var txtdata = document.getElementById('demo1');
      if(!Boolean(data)) {
        txtdata.innerText = "The box is empty.";
      } else {
        value = escape(data) + ";";
        var date = new Date();
        date.setHours(((date.getHours()) + 1)); // setting time +1 hour
        document.cookie = "name=" + value;
        document.cookie = "expires=" + date.toUTCString() + ";";
        txtdata.innerText = "Cookie is setted.";
      }
    }

    function getCookie() {
      alert(document.cookie);
    }
  </script>
</body>
</html>
Output :

At the above example the expire date is set to 1+ hour of the current time.

Reading Cookie with JavaScript :

In JavaScript the cookies can be read with the document.cookie object. The document.cookie will return all cookies in one string in key value pair. Example :
 var cookies = document.cookie;
Lest see an example :
<html>
<body>
  <input type="text" id="txtbox">
  <input type="button" onclick="setCookie()" value="Set Cookie"/>
  <input type="button" onclick="getCookie()" value="See Cookies"/> 
  <p id="demo1"></p>
  <script>

    function setCookie() {
      var data = document.getElementById('txtbox').value;
      var txtdata = document.getElementById('demo1');
      if(!Boolean(data)) {
        txtdata.innerText = "The box is empty.";
      } else {
        value = escape(data) + ";";
        var date = new Date();
        date.setHours(((date.getHours()) + 1)); // setting time +1 hour
        document.cookie = "name=" + value;
        document.cookie = "expires=" + date.toUTCString() + ";";
        txtdata.innerText = "Cookie is setted.";
      }
    }

    function getCookie() {
      var txtdata = document.getElementById('demo1');
      txtdata.innerText = document.cookie;
    }

  </script>
</body>
</html>
Output :

At the above code in getCookie() function the cookie data is grabbed with the document.cookie method.

Delete Cookie with JavaScript :

To delete a cookie, we just need to set the expiry date to a time in the past. Example :
<html>
<body>
  <input type="text" id="txtbox">
  <input type="button" onclick="setCookie()" value="Set Cookie"/>
  <input type="button" onclick="getCookie()" value="See Cookies"/>
  <input type="button" onclick="deleteCookie()" value="Delete Cookies"/> 
  <p id="demo1"></p>
  <script>

    function setCookie() {
      var data = document.getElementById('txtbox').value;
      var txtdata = document.getElementById('demo1');
      if(!Boolean(data)) {
        txtdata.innerText = "The box is empty.";
      } else {
        value = escape(data) + ";";
        var date = new Date();
        date.setHours(((date.getHours()) + 1)); // setting time +1 hour
        document.cookie = "name=" + value;
        document.cookie = "expires=" + date.toUTCString() + ";";
        txtdata.innerText = "Cookie is setted.";
      }
    }

    function getCookie() {
      var txtdata = document.getElementById('demo1');
      txtdata.innerText = document.cookie;
    }

    function deleteCookie() {
      var txtdata = document.getElementById('demo1');
      var date = new Date();
      date.setMonth(((date.getMonth()) - 1)); // set month -1
      document.cookie = "name=; expires=" + date.toUTCString() + ";";
      txtdata.innerText = "Cookie is deleted.";
    }
  </script>
</body>
</html>
Output :


At the above code the expiry date is set back to one month back, which leads to delete the cookies.


Next Topic :