Java Reference
In-Depth Information
As you'll see later, when retrieving cookie values you can use the unescape() function to convert from
the encoded version to plain text.
Back to your function; next you have an if statement.
if (cookieExpires == “”)
{
var nowDate = new Date();
nowDate.setMonth(nowDate.getMonth() + 6);
cookieExpires = nowDate.toGMTString();
}
This deals with the situation in which an empty string (“”) has been passed for the cookieExpires
parameter of the function. Because most of the time you want a cookie to last longer than the session it's
created in, you set a default value for expires that is six months after the current date.
Next, if a value other than an empty string (“”) has been passed to the function for the cookiePath
parameter, you need to add that value when you create the cookie. You simply put “path=” in front of
any value that has been passed in the cookiePath parameter.
if (cookiePath != “”)
{
cookiePath = “;Path=” + cookiePath;
}
Finally, on the last line you actually create the cookie, putting together the cookieName, cookieValue,
cookieExpires, and cookiePath parts of the string.
document.cookie = cookieName + “=” + cookieValue +
“;expires=” + cookieExpires + cookiePath;
You'll be using the setCookie() function whenever you want to create a new cookie because it makes
setting a cookie slightly easier than having to remember all the parts you want to set. More important,
it can be used to set the expiration date to a date six months ahead of the current date.
For example, to use the function and set a cookie with default values for expires and path, you just
type the following:
setCookie(“cookieName”,”cookieValue”,””,””)
Try It Out Using setCookie()
You'll now put all this together in a simple example in which you use your setCookie() function to set
three cookies named Name, Age, and FirstVisit. You then display what is in the document.cookie
property to see how it has been affected.
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<script language=”JavaScript” type=”text/JavaScript”>
Search WWH ::




Custom Search