Manipulating JavaScript Cookies

Introduction

 
In the previous chapter, we learned about cookies and how it works in JavaScript. 
 
In this chapter, we will learn about an overview of how cookies work in JavaScript and manipulating cookies in JavaScript.
 

Cookies

 
Cookies were invented by Netscape to store some information at the client-side. In web applications the web server and web browser use HTTP protocol for communication and HTTP is a stateless protocol. This means once the server sends the requested page to the browser, it does not remember a thing about it. But in real life web applications there is a need to maintain session information. To solve this problem cookies were invented. Cookies are data stored in small text files on the client-side. 
 

Working of Cookies

 
Cookies are added to the HTTP header. Then with each request and response cookies travel from browser to server and vice versa. Cookies are the small text files that contain the following fields:
  1. Name-Value pair
     
    The data in cookies are stored in the form of the ‘Name-Value’ pair. The Key is used to retrieve cookies data.
     
  2. Expiry Date
     
    Each cookie has an expiry date after which it is deleted. If the expiry date is not specified then it is deleted after the browser window is closed. The expiry date should be in UTC time.
     
  3. Secure
     
    If this file is specified as “secure,” then the cookie may only be retrieved with a secure server. This means a secure cookie will send to the server only when the request is made using SSL and the HTTPS protocol. By default, cookies set over an HTTPS connection are automatically set to be secure.
     
  4. Domain
     
    The domain field specifies that to which domain the cookie should be sent. If not specified then the domain which sets the cookies is taken. The purpose of the domain field is to allow all sub-domains access to the cookie. Consider the large networks like Yahoo with multiple sites such as mail.yahoo.com, finance.yahoo.com, etc. In this case, if I set the domain as yahoo.com then all sites in this domain can access this cookie. You can’t set the cookie domain to a domain you are not in. This means that if you are now in the yahoo.com domain and try to set domain field to google.com then it won’t work. Invalid domain options are simply ignored.
     
  5. Path
     
    The path field is used to specify the directory where the cookie is active. So if we want the cookie to be sent to pages the directory bin then sets the path to ‘/bin’. If the path is set to ‘/’, then the cookie is active for the entire domain. If the path is not specified cookie is accessible on the same page only.

Manipulating Cookies in JavaScript

 
In JavaScript, cookies can be accessed with the help of the ‘cookie’ property of the ‘document’ object. Using ‘cookie’ property you can read, create, modify delete the cookies.
  1. Storing Cookies


    To create a cookie just assign the string value to ‘cookie’ property as below.
     
    Syntax
     
    document.cookie=’key1=value1; key2=value2; expires=expiry date; path=path; secure; domain=domain’;
     
    Here expires, path, secure and domain fields are optional.
     
    Example
    1. document.cookie=’username=ranjitexpires=Thu, 18 Dec 2013 12:00:00 UTC’;   
    Note
     
    Any white spaces, commas, or semicolons are not directly allowed in the ‘name=value’ pair. If ‘name=value’ pair contains any of these, then you should encode the value before storing it with the help of escape() function. And for reading this cookie value you should use the unescape() function.
     
    Example
    1. var value=escape(document.myform.username.value) +";";    
    2. document.cookie=”username”+value;  
  2. Reading Cookies

     
    Reading is simple like writing a cookie. The property cookie returns a string that contains all ‘name-value’ pairs separated by a semicolon. Then using split() function of string we can break the whole string into key-value pairs.
     
    Example
    1. var allcookies = document.cookie;    
    2. cookiearray = allcookies.split(';');    
    3. for (var i = 0; i < cookiearray.length; i++)    
    4. {    
    5.     name = cookiearray[i].split('=')[0]; // Name of Cookie    
    6.     value = cookiearray[i].split('=')[1]; // Value of Cookie    
    7. }   
    In the above example, we get all cookies in ‘allcookies’ variable. Then we split this string into an array as ‘cookiearray’. Then we are able to use all cookies individually.
     
    You can use the following function to get the cookie by name.
    1. function GetCookie(cookiename)    
    2. {    
    3.     var name = cookiename + "=";    
    4.     var cookies = document.cookie.split(';');    
    5.     for (var i = 0; i < cookies.length; i++)    
    6.     {    
    7.         var c = cookies[i];    
    8.         while (c.charAt(0) == ' ') cc = c.substring(1, c.length);    
    9.         if (c.indexOf(name) == 0) return c.substring(name.length, c.length);    
    10.     }    
    11.     return null;    
    12. }   
  3. Deleting cookie

     
    To delete the cookie just set expiry date to a time in the past.
     
    Example
     
    Suppose we want to delete the username cookie. To delete this cookie we set the expiry date of the cookie to the previous month.
    1. var now = new Date();    
    2. now.setMonth(now.getMonth() - 1);    
    3. document.cookie = "username=;expiry=" + now.toUTCString() + ";";   

Summary

 
In this chapter, we learned why we use cookies and how to use cookies in JavaScript.
Author
Ranjit Powar
356 6.3k 1.1m
Next » Page Re-direction in JavaScript