Java Reference
In-Depth Information
secure
The final part of the cookie string is the secure part. This is simply a boolean value; if it's
set to true the cookie will be sent only to a web server that tries to retrieve it using a secure
channel. The default value, which is false , means the cookie will always be sent, regardless
of the security. This is only applicable where you have set up a server with SSL (Secure
Sockets Layer).
Creating a Cookie
To make life easier for yourself, you'll write a function that enables you to create a new cookie
and set certain of its attributes with more ease. This is the first of a number of useful functions
you'll create and add to a separate .js file so you can easily reuse the code in your future projects.
You'll look at the code first and create an example using it shortly. First create a file called
cookiefunctions.js and add the following to it:
function setCookie(name, value, path, expires) {
value = escape(value);
if (!expires) {
var now = new Date();
now.setMonth(now.getMonth() + 6);
expires = now.toUTCString();
}
if (path) {
path = ";Path=" + path;
}
document.cookie = name + "=" + value + ";expires=" + expires + path;
}
The secure and domain parts of the cookie string are unlikely to be needed, so you allow just the
name , value , expires , and path parts of a cookie to be set by the function. If you don't want to set
a path or expiration date, you can omit them or pass empty strings for those parameters. If no path
is specified, the current directory and its subdirectories will be the path. If no expiration date is set,
you just assume a date six months from now.
The first line of the function introduces the escape() function, which you've not seen before:
value = escape(value);
When we talked about setting the value of a cookie, we mentioned that certain characters cannot
be used directly, such as a semicolon. (This also applies to the name of the cookie.) To get
around this problem, you can use the built‐in escape() and unescape() functions. The escape()
function converts characters that are not text or numbers into the hexadecimal equivalent of their
character in the Latin‐1 character set, preceded by a % character.
 
Search WWH ::




Custom Search