Subscribe via RSS Feed

JavaScript and Cookies

April 11, 2014 1 Comment

Web Browser and Servers use HTTP protocol to communicate. HTTP is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. Cookies are bits of data that a browser stores in visitor’s computer. When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user. Cookies were invented to solve this problem.

When a user visits a web page, his name can be stored in a cookie. Next time the user visits the page, the cookie “remembers” his name. Cookies were originally invented by Netscape to give ‘memory’ to web servers and browsers.A cookie is basically a string of text characters not longer than 4 KB. Cookies are set in ‘name=value’ pairs separated by semi-colons. When server sends some data to the visitor’s browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor’s hard drive. Now, when the visitor arrives at another page on the site, the browser sends the same cookie to the server for retrieval. Once retrieved, server remembers what was stored earlier.

Cookies were originally designed for CGI programming and cookies’ data is automatically transmitted between the web browser and web server, so CGI scripts on the server can read and write cookie values that are stored on the client.JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page.

"max-age=60; path=/;"

Cookies have, by default, a lifespan of the current browser session. As soon as visitor closes his browser, cookie disappears. To make it last longer, we need to set the max-age variable to contain the number of seconds we want the cookie to last.

By default, cookies are valid only for web pages in the directory of the current web page that stored them, as well as its descendants. If we want the cookie to be valid in some other directory, like http://, we need to set the path variable to contain the value “/ dirname “.

Another special variable is the domain variable. Cookies set in sub-domains like will only be valid for that subdomain. If you want it to be valid for all sub-domains of, you will need to set the domain to point to ””.

Secure :
If this field contains the word “secure” then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.

Storing Cookies:
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this:

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

Cookie values may not include semicolons, commas, or whitespace. For this reason, we should use the JavaScript escape() function to encode the value . We have to use the unescape() function when we need to read the cookie value, if we have used escape() function to encode the value previously.

Reading Cookies:
Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So we are able to use this string whenever we want to access the cookie.

function ReadCookie()
   var cookies = document.cookie;
   alert("Cookies : " + cookies );
   cookiearray  = cookies.split(';');

   for(var i=0; i<cookiearray.length; i++){
      name = cookiearray[i].split('=')[0];
      value = cookiearray[i].split('=')[1];
      alert("Key is : " + name + " and Value is : " + value);

Setting the Cookies Expiration Date:
We can extend the life of a cookie beyond the current browser session by setting an expiration date. We can also save the expiration date in the same cookie. This can be done by setting the ‘expires’ attribute to a date and time. Instead of setting date, we can see new time using setTime() function.

function WriteCookie()
   var sampledate = new Date();
   sampledate.setMonth(sampledate.getMonth() + 1 ); 
   cookievalue = escape(document.myform.example.value) + ";"
   document.cookie="name=" + cookievalue;
   document.cookie = "expires=" + now.toUTCString() + ";"
   alert("Setting Cookies : " + "name=" + cookievalue );

Check a Cookie:
The simplest way to check for cookies is via JavaScript. The following function will return a boolean value — true if cookies are enabled:

function are_cookies_enabled()
	var cookieEnabled = (navigator.cookieEnabled) ? true : false;

	if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
		cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
	return (cookieEnabled);

Deleting a Cookie:
There are times when we have to delete a cookie, such as when a visitor logs out from the site. To do this, we have to set the max-age variable to 0 (zero) for the same cookie in the same path and domain. We can see the process of doing so in the following function :

function delete_cookie ( cookie_name, valid_domain )
var domain_string = valid_domain ?
("; domain=" + valid_domain) : '' ;
document.cookie = cookie_name +
"=; max-age=0; path=/" + domain_string ;

If you find this article helpful, you can connect us in Google+ and Twitter.

Enter your email address:

Delivered by FeedBurner

Sign Up to read the rest of the content

Email will be used only for updates of our site

No Thanks

Filed in: Open Source Technologies • Tags: