Pages

Cookies in action

We can use the cookie functions we have just written to improve again our interactive page giving it a way of remembering the user name, so to use it even when the user return to the page after a while.

First thing, we store the utility function in a text file in the same directory of our HTML page. The usual extension for JavaScript is js, so we call it "cookie.js". Then to include it in the HTML page we use this directive:
<script type="text/javascript" src="cookie.js"></script>

Now we modify the existing code, in the already existing script tag. First step is adding a constant, to define the name of the cookie we are about to use:

<script type="text/javascript">
var userName;
const COOKIE_NAME = "name";

<!-- ... -->

The navigator.cookieEnabled flag tells us if we have it available. Only if it is true we can work with them. So, we modify the greet() function to read the user name stored in the cookie (when possible), if have a name we use it to greet the user, otherwise to use a anonymous way to greeting him:

function greet() {
if(navigator.cookieEnabled)
userName = readCookie(COOKIE_NAME);

if(userName) {
alert("Hello " + userName + ", I missed you.");
setHappy(true);
}
else
alert("Hello from a whimsical page!");
}

Then we rewrite the touchMe() function, moving the input request in the getName() function:

function getName() {
userName = prompt("What is your name?", "Enter your name here.");
if (userName) {
alert("Nice meeting you, " + userName + ".");
if(navigator.cookieEnabled)
writeCookie(COOKIE_NAME, userName, 30);
else
alert("Cookie not enabled - I won't remember you for long.");
}
}

function touchMe() {
if (userName)
alert("I like the attention, " + userName + ". Thank you.");
else
getName();

setHappy(true);
}


More on JavaScript cookies in chapter three of Head First JavaScript.

No comments:

Post a Comment