JavaScript – Cookies

You may have visited a website that pops up a message saying something like ‘this site uses cookies’. So what are they? That is what we would learn in this tutorial.

  1. What are Cookies
  2. How Cookies Work
  3. How to Store Cookies
  4. How to Read Cookies
  5. Setting Cookie Expiry Date
  6. Deleting a Cookie

 

1. What are Cookies

When you surf the internet using your browser, your browser communicate with a remote server using the HTTP. This is known as a stateless protocol. Being stateless means that the server no information about your browsing is stored.This information is called session data or session information. Infact, the server does not remember the last page you visited! At least, that is what it is supposed to be. However, for some websites, some information has to be stored. For example, if you logged in the first time, then some information about you is stored so you don’t need to login after every page visit. Typical example is an online store.

In situations like this and many others, the way to keep track of relevant information by the use of cookies. The provides a better user experience. Besides site statistics can be kept as well.

 

2. How Cookies Work

When the browser starts interacting with the server, the server sends some data to the browser. This little piece of information is called a cookie. If the browser accepts the cookie, then it is stored as a plain text in the users computer. So when the visitor visits another page, the browser sends this piece of information to the server. The server checks this information and uses it to remember who the user is.

Cookies are stored in a record of 5 fields namely:

  • Domain − The domain name of the visited site.
  • Path − The path to the directory or web page that sets the cookie. This could be empty if you want to retrieve the cookie from any directory or page.
  • Secure − If this field contains the word “secure”, then the cookie can only be retrieved with a secure server. If however this field is blank, then no such restriction exists.
  • Name=Value − Cookies are set and retrieved in the form of key-value pairs of name and value
  • Expires − This is the date the cookie will expire. If it is empty, then the cookie will expire when the visitor closes the browser.

JavaScript being a scripting language can be  used to read, write and modify cookies for the current web page. That is what we would learn in the next examples. JavaScript uses the Document object to manipulate cookies.

 

3. How to Store Cookie

To create a cookie using JavaScript, simply assign the cookie value using the document.cookie object. The syntax for this is given below:

document.cookie = "key1 = value1;key2 = value2;expires = date";

The expired field is optional. So if you provide it (a date and time), then the cookie will expire on the specified date. However, if you omit it, then the cookie expires when the user exits the browser. When a cookie expires, it will no longer be accessible.

To Note: Values of cookies may not contain a whitespace, commas or semicolon. That is why, to write a cookie, you need to use the escape() function. Similarly when reading a cookie you may use the unescape() function

The example below create a cookie and sets its value to the name of the customer

<html>
   <head>  
   <title>Cookies Demo</title>   
      <script type = "text/javascript">
         <!--
            function WriteCookie() {
               if( document.myform.customer.value == "" ) {
                  alert("Enter some text!");
                  return;
               }
               cookievalue = escape(document.myform.customer.value) + ";";
               document.cookie = "name=" + cookievalue;
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>     
   </head>
   
   <body>
      <form name = "myform" action = "">
         Enter your name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
      </form>       
   </body>
</html>

Test the page, you will have a text box and a button. Enter some value in the text box and click on the button. Then a cookie is set on your computer!

 

4. How to Read Cookies

Similar to writing a cookie, we can also read a cookie. The cookie are gotten by accessing the document.cookie object. The document.cookie provides a string of all the name-value pairs in the cookie each pair separated by a semicolon.

So you can split up the this string into cookies using the split() function passing it a semicolon as parameter.

<html>
   <head>   
      <script type = "text/javascript">
         <!--
            function ReadCookie() {
               var cookies = document.cookie;
               document.write ("Cookies : " + cookies );
               
               // Splie the cookie and get cookies pairs as an array
               cookiearray = cookies.split(';');
               
               // Split the cookies into key and value
               for(var i=0; i<cookiearray.length; i++) {
                  name = cookiearray[i].split('=')[0];
                  value = cookiearray[i].split('=')[1];
                  document.write ("Key is : " + name + " and Value is : " + value);
               }
            }
         //-->
      </script>      
   </head>
   
   <body>     
      <form name = "myform" action = "">
         <p> click on the button and see the result:</p>
         <input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
      </form>      
   </body>
</html>

Try the code above. When you click on the button, all the cookies set in your computer is displayed.

 

5. Cookie Expiry Date

The cookies we create in the previous examples does not provide any expiry date. Now we would create a cookie and specify an expiry date. You do this by setting the ‘expires’ attribute’ of the cookie.

The example below creates a cookie and sets the expiry date to 7 days from now. Therefore, the cookie would stay for 1 week.

<html>
   <head>  
   <title>Cookies Demo</title>   
      <script type = "text/javascript">
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setDate( now.getDate() + 1 );
               cookievalue = escape(document.myform.customer.value) + ";"
               
               document.cookie = "name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write ("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>  
   </head>
   
   <body>
      <form name = "myform" action = "">
         Enter your name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
      </form>       
   </body>
</html>

 

6. Deleting a Cooking

Finally, you can also delete a cookie before it actually expires. When a cookie is deleted, then it is no longer accessible. One way to delete a cookie is to set the ‘expires’ attribute to a time in the past.

I would leave this to you as an exercise!