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.


<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
var the_date = new Date("December 31, 2005");

//  converting this date to a GMT String
var the_expiration = the_date.toGMTString();

alert(the_name + " expires " + the_expiration);

//  accumulating the name cookie along with its expiration date
var the_cookie = "my_cookie=" + escape(the_name);
the_cookie = the_cookie + ";expires=" + the_expiration;
document.cookie = the_cookie;


<body bgColor="666699" text ="330033">

<table align="center" width="300">
<td align="center"><input type="Button" value="Set The Cookie" onClick="setCookie();"></td>


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


to your cookie.

If you want an entire site to access the cookie then you need to add something like


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.