Java Reference
In-Depth Information
Using setCookie()
trY it out
You 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.
Open your text editor and type the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 13: Example 1</title>
</head>
<body>
<script src="cookiefunctions.js"></script>
<script>
setCookie("Name", "Bob");
setCookie("Age", "101");
setCookie("FirstVisit", "10 May 2007");
alert(document.cookie);
</script>
</body>
</html>
Save the example as ch13 _ example1.html and load it into a web browser.
You'll see the alert box shown in Figure 13-17. Note
that all three cookies are displayed as name / value pairs
separated from the others by semicolons, and also that
the expiration date is not displayed. If you had set the
path parameter, this also would not have been displayed.
The UserName cookie from a previous example is also
displayed.
figure 13-17
You already know how the setCookie() function works, so
let's look at the three lines that use the function to create three
new cookies:
setCookie("Name", "Bob");
setCookie("Age", "101");
setCookie("FirstVisit", "10 May 2007");
It is all fairly simple. The first parameter is the name that you'll give the cookie. (You see shortly how
you can retrieve a value of a cookie based on the name you gave it.) It's important that the names you
use be only alphanumeric characters, with no spaces, punctuation, or special characters. Although you
can use cookie names with these characters, doing so is more complex and best avoided. Next you have
the value you want to give the cookie. The third parameter is the path, and the fourth parameter is the
date on which you want the cookie to expire.
Search WWH ::




Custom Search