|
Cookies have been the subject of a lot of controversy right from the time Netscape incorporated it into it's browser. A cookie is a small piece of information that a web page can store on your machine and retrieve it on your subsequent visits. To protect your privacy, a cookie set by one particular site cannot be accessed by another site. So if you had any plans to surprise your visitors with messages like "I know what you did yesterday blah blah blah...", you can forget it right now. To learn how to use cookies in Javascript, I went to Netscape's Javascript Guide and found these two functions that I thought were very useful. I have modified it to make it look simpler but the functionality is essentially the same.
<HEAD> and </HEAD> tags in your
HTML file. But before you start using these functions, it would be a
good idea to understand how these functions work.
A cookie basically consists of three pieces of information: a variable
name, an associated value and an expiration date. For example, when a
person visits your web page, you can have a form asking his/her name
and save it as a cookie so that you can greet your visitors by name
on their subsequent visits. In this case, you would create a cookie
called 'visitor' and assign it the value the user enters in the form
and set the expiration date to a few months ahead of the current day.
You access cookies by using the visitor and
set it's value to 'yoda' and this cookie will be active till the year
2001. The expires part is actually optional and if it is
left out, the cookie you create will expire as soon as the browser
window is closed.
The
Once you save the cookie, the value of
This example is getting pretty long and the complex part is just
beginning. Reading a cookie back is not as simple as writing a
cookie because if you ask for the value of
You will see the cookie you set earlier, but you will also see other cookies
that this page automatically sets. (These cookies are used by the banners on this
page to make sure that the same banner does not get diplayed over and over again).
Extracting the value of a particular cookie out of this mess can be tiresome
but fortunately we already have the
See Also:
|
|