Expiration and Access of Cookies
Introduction. By default, cookies expire at the end of a session and are only accessible from the page where they were instituted. Over-riding the defaults isn't difficult, but it requires some more knowledge and experience. We will create a simple page that uses a prompt( ) to get the user's name. Then we will write a cookie so that this page could retrieve this name automatically using some code whenever this computer's user revisits this page. You should copy the following code into a file called NameExpireCookie.html. |
<html> <head> <title>Get Name and Set Expiration</title> <script language="JavaScript"> function setCookie() { // using a prompt( ) to get the user's name var the_name = prompt("What's your name?",""); // setting a date to the end of 2005 // converting this date to a GMT
String // accumulating the name cookie along
with its expiration date |
There are a few alert( ) functions in the code to give
you feedback about what has happened at particular steps. After uploading and accessing this page and entering your name, you should see something like the following at some step in the process. |
Depending on whether you are using Netscape or Internet Explorer you should find the following files and then look inside to see the new cookie. |
Browser | Find File Name |
Netscape | cookies.* |
Internet Explorer | cookies |
After finding and isolating on particular aspects of what you find, you should see something like the following. I worked this problem in Internet Explorer so the cookie is in its own file in a directory for cookies. |
Accessing Cookies.
Who can access the cookies using JavaScript? By default, only the
web page that set the cookie can access it. If you want to be able
to have other pages in a directory on the host server access the page
then you need to add something like
path=/directoryName to your cookie. If you want an entire site to access the cookie then you need to add something like domain=domainName to your cookie. The book claims that yahoo allows all of its affiliate sites to access yahoo related cookies by adding domain=yahoo.com to all of their cookies. |