Using Cookies
Cookies are a mechanism for storing persistent data on the client in a file called cookies.txt. Cookies are small fragments of information that are written to the user’s hard disk and can be retrieved anytime before its expiry by a web page.
name=value;expires=expDate;
name is the name of the datum being stored, and value is its value. If name and value contain any semicolon, comma, or blank (space)
characters, you must use the escape function to encode them and the unescape function to decode them.
expDate is the expiration date, in GMT date format:
Wdy, DD-Mon-YY HH:MM:SS GMT
Although it's slightly different from this format, the date string returned by the Date method toGMTString can be used to set cookie expiration dates.
The expiration date is an optional parameter indicating how long to maintain the cookie. If expDate is not specified, the cookie expires
when the user exits the current Navigator session. Navigator maintains and retrieves a cookie only if its expiration date has not yet passed.
For more information on escape and unescape, see the JavaScript Reference.
Limitations
Cookies have these limitations:
300 total cookies in the cookie file.
4 Kbytes per cookie, for the sum of both the cookie's name and value.
Cookies can be associated with one or more directories. If your files are all in one directory, then you need not worry about this. If your files are in multiple directories, you may need to use an additional path parameter for each cookie.
Using Cookies with JavaScript
The document.cookie property is a string that contains all the names and values of all cookies. You can use this property to work with cookies in JavaScript.
Here are some basic things you can do with cookies:
Set a cookie value, optionally specifying an expiration date.
Get a cookie value, given the cookie name.
It is convenient to define functions to perform these tasks. Here, for example, is a function that sets cookie values and expiration:
// Sets cookie values. Expiration date is optional
//
function setCookie(name, value, expire) {
document.cookie = name + "=" + escape(value)
+ ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
}
Notice the use of escape to encode special characters (semicolons, commas, spaces) in the value string. This function assumes that cookie names do not have any special characters.
The following function returns a cookie value, given the name of the cookie:
function getCookie(Name) {
var search = Name + "="
if (document.cookie.length > 0) { // if there are any cookies
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))
}
}
}
Notice the use of unescape to decode special characters in the cookie value.
Using Cookies: an Example
Using the cookie functions defined in the previous section, you can create a simple page users can fill in to "register" when they visit your
page. If they return to your page within a year, they will see a personal greeting.
You need to define one additional function in the HEAD of the document. This function, register, creates a cookie with the name
TheCoolJavaScriptPage and the value passed to it as an argument.
function register(name) {
var today = new Date()
var expires = new Date()
expires.setTime(today.getTime() + 1000*60*60*24*365)
setCookie("TheCoolJavaScriptPage", name, expires)
}
The BODY of the document uses getCookie (defined in the previous section) to check whether the cookie for TheCoolJavaScriptPage exists and displays a greeting if it does. Then there is a form that calls register to add a cookie. The onClick event handler also calls history.go(0) to redraw the page.
<BODY>
<H1>Register Your Name with the Cookie-Meister</H1>
<P>
<SCRIPT>
var yourname = getCookie("TheCoolJavaScriptPage")
if (yourname != null)
document.write("<P>Welcome Back, ", yourname)
else
document.write("<P>You haven't been here in the last year...")
</SCRIPT>
<P> Enter your name. When you return to this page within a year, you will be greeted with a personalized greeting.
<BR>
<FORM onSubmit="return false">
Enter your name: <INPUT TYPE="text" NAME="username" SIZE= 10><BR>
<INPUT TYPE="button" value="Register"
onClick="register(this.form.username.value); history.go(0)">
</FORM>