Cookies are the JavaScript mechanism for storing information for a long
period of time. They are strings that are stored in files on the hard
drives of surfers' computers. Cookies are the only mechanism by which
JavaScript programs can read and write information to a surfer's hard
drive.
Cookies come in handy when you want information generated during one
visit to your site to be available during another visit to your site, or
when you want information generated on one page of your site to be
available to scripts on another page of your site. Let's take a look at
the mechanics of setting cookies.
Cookies are created by setting the document.cookie property equal to a
properly formatted string. When you create a cookie, you must specify at
least its name and its value. Additionally, you can specify some other
characteristics of the cookie. If you want to make a cookie persist
beyond the current browser session, you must specify an expiry date for
the cookie.
The syntax for setting a no-frills cookie with only a name-value pair
looks like this:
document.cookie = "name=value";
Then, to make the cookie persistent, you have to specify a date and
time, as formatted by the toGMTString() method of the Date object. So,
create a date, apply the toGMTString() method to it, and concatenate the
results onto the name-value pair, separating the two with a semicolon.
Therefore, if you had stored the results of your toGMTString() operation
in a variable called expiryDate, your cookie-setting statement would
look like this:
document.cookie = "name=value;" + expiryDate;
You can retrieve the name-value pair (but not the expiry date) by
reading document.cookie from another page.