Tuesday, 28 February 2012

JavaScript cookies

Some Web sites stored some information with a small text file in user hard disk , these files are known as cookies. In JavaScript  cookie is  a property of document object.   JavaScript  provides comprehensive access rights of Cookies. 
Before continuing, we need to learn the basic of a cookie.
  Each Cookie has an expiry date, once the computer clock cross the expiration date, the cookie will be deleted. We can not directly delete a cookie, but you can set the expiration date earlier  to indirectly delete it. 
  Each page, or that each site has its own cookies, these cookies can only access by this site's pages and pages from other sites or the same site, an unauthorized region i.e. from a different browser can not access .
  Now we will learn to use the document.cookie property . 
  If you directly use the document.cookie property, or, in some way, for example, assign the variables to the value of document.cookie, we can know how many Cookies are in the present document, the name of each Cookies, and its value. For example, in a document to add document.write (document.cookie) ", the results showed that:

document.cookie="NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN; secure"; 
name and value : The first part of the cookie string must have the name and value.

encodeURIComponent() and decodeURIComponent() functions.
To ensure that  cookie value string does not contain any commas, semicolons, or whitespace characters use  encodeURIComponent () function. Use  decodeURIComponent() function is used to  decode the encoded string by encodeURIComponent() functions.

expires : To give more life to the cookies you must set an expiration date in the following format. DD-Mon-YY HH:MM:SS GMT

Here is an example where the cookie will live upto Sun, 12 Jun 2012:00:00:00 GMT

path : To set a cookie in a specified path called 'backup' under root use the following command.

document.cookie= "VisiterName=George;expires=Mon,12Jun2011:00:00:00"
+ ";path=/backup;"; domain : To set the cookie in a domain name myexample.com