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:
- Name-Value pair
The data in cookies are stored in the form of ‘Name-Value’ pair. Key is used to retrieve cookies data.
- 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.
- 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.
- 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.
- 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.
- 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:
- 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:
- var value=escape(document.myform.username.value) +";";
- document.cookie=”username”+value;
- 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:
- var allcookies = document.cookie;
- cookiearray = allcookies.split(';');
- for (var i = 0; i < cookiearray.length; i++)
- {
- name = cookiearray[i].split('=')[0];
- value = cookiearray[i].split('=')[1];
- }
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.
- function GetCookie(cookiename)
- {
- var name = cookiename + "=";
- var cookies = document.cookie.split(';');
- for (var i = 0; i < cookies.length; i++)
- {
- var c = cookies[i];
- while (c.charAt(0) == ' ') c = c.substring(1, c.length);
- if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
- }
- return null;
- }
- 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.
- var now = new Date();
- now.setMonth(now.getMonth() - 1);
- 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: