Java Reference
In-Depth Information
The value for the cookie is a primitive string, although the string can hold number characters if it is
numerical data that you want to store. If you are storing text, certain characters, such as semicolons,
cannot be used inside the value, unless you use a special encoding, which you'll see later. In the case of
semicolons, this is because they are used to separate the different parts of the cookie within the cookie
string.
In the following line of code, you set a cookie with the name UserName and the value Paul.
document.cookie = “UserName=Paul;”;
This cookie has a very limited lifespan , which is the length of time the information will continue to
exist. If you don't set an expiration date, a cookie will expire when the user closes the browser. The
next time the user opens the browser the cookie will be gone. This is fi ne if you just want to store
information for the life of a user session , which is a single visit by the user to your web site. However,
if you want to ensure that your cookie is available for longer, you must set its expiration date, which
you'll look at next.
expires
If you want a cookie to exist for longer than just a single user session, you need to set an expiration date
using the second part of the cookie string, expires, as follows:
document.cookie = “UserName=Paul;expires=Tue, 28 Dec 2020 00:00:00 GMT; “;
The cookie set by the previous line of code will remain available for future use right up until
December 28, 2020.
Note that the format of the expiration date is very important, especially for IE browsers. It should be
the same format the cookie is given by the toGMTString() method. This method is similar to the
toUTCString() method that you saw in Chapter 10.
In practice, you'll probably use the Date object to get the current date, and then set a cookie to
expire three or six months after this date. Otherwise, you're going to need to rewrite your pages
on December 28, 2020.
For example, you could write the following:
var expireDate = new Date();
expireDate.setMonth(expireDate.getMonth() + 6);
document.cookie = “UserName=Paul;expires=” + expireDate.toGMTString() + “;”;
This will create a new cookie called UserName with the value of Paul, which will expire six months
from the current date. Note that other factors can cause a cookie to expire before its expiration date,
such as the user deleting the cookie or the upper cookie limit being reached.
path
You'll fi nd that 99 percent of the time you will only need to set the name, value, and expires parts of a
cookie. However, at times the other three parts, such as the path part that you are looking at in this
Search WWH ::




Custom Search