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() {
userName = readCookie(COOKIE_NAME);

if(userName) {
alert("Hello " + userName + ", I missed you.");
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 + ".");
writeCookie(COOKIE_NAME, userName, 30);
alert("Cookie not enabled - I won't remember you for long.");

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


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

No comments:

Post a Comment