Overview Of JavaScript Cookies

Cookies

Cookies were invented by Netscape to store some information atthe 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 browser, it does not remember a thing about it. But in real life web applications there isa 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 in 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 ‘Name-Value’ pair. Key is used to retrieve cookies data.

  2. Expiry Date

    Each cookie has an expiry date after which it is deleted. If expiry date is not specified then it is deleted after the browser window is closed. Expiry date should be in UTC time.

  3. Secure

    If this file is specified as “secure,” thenthe cookie may only be retrieved witha secure server. This means a secure cookie will send to server only whenthe  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 domain field is to allow all sub-domains the access tothe 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 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 set the path to ‘/bin’. If path is set to ‘/’ , then cookie is active for entire domain. If path is not specified cookie is accessible on same page only.

Manipulating Cookies in JavaScript

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

  1. Storing Cookies

    To create 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=ranjit; expires=Thu, 18 Dec 2013 12:00:00 UTC’;  
    Note: Any white spaces, commas, or semicolons are not directly allowed in ‘name=value’ pair. If ‘name=value’ pair contain 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 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 which contains all ‘name-value’ pairs separated by semicolon. Then using split() function of string we can break 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 above example we get all cookies in ‘allcookies’ variable. Then we split this string into 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) == ' ') c = 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 inthe past.

    Example:

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

Conclusion

In this article we learned why we use cookies and how to use cookies in JavaScript.

Read more articles on JavaScript:

Up Next
    Ebook Download
    View all
    Learn
    View all