HTML and CSS Reference
In-Depth Information
When you reload the page, the
document.cookie
property will contain all the cookie
text saved for that page.
To create a cookie, assign the
name=value
pairs to the
document.cookie
property. Be care-
ful with quotes, making sure the variables you use are not quoted, but the text that the
cookie needs, such as the word
“name”
, and
“=”
are quoted. Also, this will be a big string
where the different parts are concatenated together with the + operator. The following
format sets a cookie using all possible attributes. Those attributes enclosed in square
brackets are optional:
FORMAT
name=value;[expires=date];[path=path];[domain=somewhere.com];[secure]
EXAMPLE
document.cookie="id=" + form1.cookie.value ";expires=" +
expiration_date+";path=/";
The
escape()
and
unescape()
Built-In Functions.
It is important to know that
when assigning string
name=value
attributes to a cookie, you cannot use whitespace,
semicolons, or commas. The
escape()
function will encode the string object by convert-
ing all nonalphanumeric characters to their hexadecimal equivalent, preceded by a per-
cent sign; for example,
%20
represents a space and
%26
represents an ampersand. To
send information back and forth between browser and server, the browser encodes the
data in what is called URI encoding. You can see this encoding in the location bar of your
browser; when you go to Google and search for something, you will see the search string
in the location bar of the browser all encoded. Because the browser handles cookies, the
cookie strings can be encoded with JavaScript's built-in
escape()
function to ensure that
the cookie values are valid.
The
unescape()
function converts the URI-encoded string back into its original for-
mat and returns it. The
encodeURI()
and
decodeURI()
built-in functions are a more
recent version of
escape()
and
unescape()
and do not encode as many characters.
EXAMPLE
16.1
<html>
<head>
<title>The escape() Method</title>
<script type="text/javascript">