JavaScript Cookies
Description
JavaScript Cookies are a great way to save a user's preferences in his / her browser. This is useful for websites and users both, if not used to steal privacy.
A cookie is a small piece of text stored on the visitor's computer by a web browser. As the information is stored on the hard drive it can be accessed later, even after the computer is turned off.
A cookie can be used for authenticating, session tracking, remember specific information about user like his name, password, last visited date etc.
As cookies are simple piece of text they are not executable. In javaScript we can create and retrieve cookie data with JavaScript's document object's cookie property.
You can set a cookie setting document.cookie to a cookie string. Later we will discuss details how to create and retrieve a cookie.
Example of cookies
Here is an simple example where have set a cookie with the UserName as George, and an expiration date of Mon, 14 July 2011.
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> </head> <body> <script type="text/javascript"> //This is done to make the following JavaScript code compatible to XHTML. <![CDATA[ document.cookie = "UserName=George; expires=Mon, 14 July 2011 00:00:00;"; //]]> </script> </head> <body>
What cookies cannot do ?
- The first is that all modern browser support cookies, but user can disable them. In IE, go to Tools and select Internet options, a window will come. Click on privacy and select advanced button, another new window will come, from here you can disable cookie.
- Cookies can identify the computer being used, not the individual.
- Most modern browser is expected to be able to store at least 300 cookies of four kilobytes (4 kb) per server or domain.
- For each domain and path you can store upto 20 cookies.
- Cookies cannot accessed by any other computer except the visitor's computer that created cookie.
- A website can set and read only its own cookies (for example, Yahoo can’t read IE's cookies).

