logo

client side cookies JavaScript

JavaScript: The Definitive Guide
Author David Nishimoto
davepamn@relia.net
Subject: client side cookies

Overview: Cookies temporary store information on the clients machine. The server application can request information stored in the cookie at a later time if the cookie hasn't expired.


<html><head><title>Cookie</title>
<SCRIPT language="JavaScript">
// Sets cookie values. Expiration date is optional
function setCookie(name, value, expire) 
{
   document.cookie = name + "=" 
   + escape(value) 
   + ((expire == null) ? "" : ("; expires=" 
   + expire.toGMTString() ) )
}
function getCookie(name) 
{
   var search = name + "="
   if (document.cookie.length > 0) {
      offset = document.cookie.indexOf(search)
      if (offset != -1) { // if cookie exists
         offset += search.length
         // set index of beginning of value
         end = document.cookie.indexOf(";", offset)
        // set index of end of cookie value
        if (end == -1)
           end = document.cookie.length
        return unescape(document.cookie.substring(offset, end))
      }
}
function deleteCookie (name) 
{
	// The function simply checks to see if the cookie is set.
	// If so, the expiration date is set to Jan. 1st 1970.
	if (getCookie(name)) 
	{
document.cookie = name + "=" +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

}
}
</SCRIPT>
<script language=javascript>
function runCookie()
{
setCookie('test','Hello World',null);
alert(getCookie('test'));
}
</script>
</head>
<body onLoad="runCookie();">
</body>
</html>
</pre>
<h3>Cookie Parameters</h3>
<p>
The "date" parameter must be in the format as returned by the toGMTString() method of the date object. 
The expires attribute is optional; not setting this will mean that the cookie will expire when the user 
shuts down their browser. If set, the cookie survives until the set expire date. 
<h3>Cookie Security</h3>
<P>
"domainName" sets the cookie's visibility to a particular domain although this attribute 
is rarely used as it defaults to the domain of the carrying document and visibility of the cookie is normally restricted to this document alone. 
The path parameter is similar to domain in that it restricts the cookie's visibilty to the specified directory on the web server. 
The secure attribute is less commonly used. 
If the secure attribute is used, a Boolean (true or false), and when true the 
browser makes secure (SSL) URL requests when the cookie is sent to the server. 
s