Lesson 15: Useful Tasks (I) – Setting and Retrieving Cookies

By Maria Antonietta Perna

You've come a long way in this tutorial. You're ready to look more closely at how JavaScript performs a real world task: setting and retrieving cookies.

In this lesson, you will learn:

  • what a cookie is;
  • how you can store cookies on your website visitors' computer;
  • how you can retrieve the cookie and use the values stored in it on the web page.

In the process, you will have occasion to use the global escape() function, the split() method of the String object, and the toGMTString() method of the Date object.

What's a cookie?

The values stored in JavaScript variables are destroyed as soon as the browser is closed or the page is reloaded. Therefore, if you use an input box on your web page to store visitors' names in a variable, that value is lost as soon as they leave the page.

A common feature present in most websites today is some sort of personalization mechanism whereby web visitors are recognized. Some instances of this personal touch can be things like greeting returning visitors by their name, indicating how long it's been since the last visit to the website, showing some products that might be of interest to the user based on past purchases, etc.

As you might have guessed, we're dealing with values, and if we want to use them in our JavaScript program, we need a storage place for them. However, all storage places examined so far are temporary. We need something that persists in between visits to our web page.

This is where cookies enter the scene.

Cookies are strings of text containing small pieces of data about your website visitors. They are stored by the browser in your visitors' computers. Each cookie has a name and an expiration date, and is separated from other cookies by a semicolon ( ; ). The fact that cookies are all stored in the same place, retrieving a specific cookie out of the collection to read its values calls for some little work on our part.

However, before we can retrieve a cookie, we need to write one and store it in the visitor's browser.

How do I set cookies with JavaScript?

Cookie data is stored in the document object's cookie property. The data is stored as "name=value" pairs, in which the values may not contain any whitespace, commas ( , ) and semicolons ( ; ). This is why we use the escape() method, which enables us to encode the string in Unicode format (e.g., a space is represented as %20).

By default the lifespan of cookies is limited to the current browser session. However, by setting an expiry date in the form of an "expires=date" pair, we can prolong the cookie's life (unless the user decides to delete the cookies stored on her machine). The date value is a GMT string, which can be obtained by using the Date object and its toGMTString() method.

If you insert the code snippet below inside enclosing <script> tags of an HTML page, you set a cookie named "myCookie" on your visitor's computer, that expires after a minute starting from the time of its creation:

		//If no cookie is present, we create one
		if (! document.cookie)
		var cookieName = "Test Cookie";
		//escape the string to make sure there are
		//no unallowed characters
		var myCookie = escape(cookieName);
		//set the expiry date to 1 minute from creation date:
		//get current date and add 1 minute reduced to milliseconds:
		var expiryDate = new Date();
		expiryDate.setTime(expiryDate.getTime() + (60 * 1000));
		//create the myCookie cookie and add it
		//to the cookie property of the document object:
		//in name=value pairs separated by ;
		document.cookie = "myCookie=" + myCookie + ";" + "expires=" + expiryDate.toGMTString() + ";";
		//leave a message to the user:
		document.write("Thank you, " + cookieName + " is your cookie");

That's all set. The browser running a page containing the code snippet above, will store a cookie by the name "myCookie" with a value of "Test Cookie", that expires after 1 minute.

How do I retrieve and use cookies in my web page?

Retrieving cookies to read their values requires the use of a couple of methods. First, you need to unescape the name value that you previously escaped. This means that, if your name value contained a space, it was escaped by replacing the space with %20. Now that you're reading the value back from the cookie name, you need to replace %20 with a space character. This is easily done with the unescape() method.

Secondly, you need to extract each name-value pair separately from the cookie string. You do this with the split() method of the String object.

split() is used to split a string into an array of comma ( , ) separated substrings. It takes an optional argument called separator. This specifies the character to use for splitting the string.

The code snippet below will check if cookies are present in the cookie property of the document object. If they are, the script extracts and displays the values of the "myCookie" cookie.

		//continue from the previous code snippet
		var myCookieString = unescape(document.cookie);
		//create a comma-separated array of substrings from the string
		//containing the cookie values by using
		//split() with "=" as separator.
		//Remember name/value pairs in the cookie
		//string are separated by an = sign:
		var dataList = myCookieString.split("=");
		//check that the name at index position 0 is
		//"myCookie" (remember the cookie name from previous example):
		if (dataList[0] === "myCookie")
		//let's extract the value of myCookie
		//by using split() once again.  Now the items in
		//dataList array are separated by " , ".
		//This will be our separator in the split() method.
		//Item 1 (index 0) is the cookie name,
		//item 2 (index 1) is the value, which is what we need:
		var data = dataList[1].split(",");
		//Now we have a new array of strings called data.
		//containing only the cookie value ("Test Cookie"),
		//which is at index 0.  We extract it:
		var cookieName = data[0];
		//Now we display a personalized greeting
		document.write("Welcome back, here's your cookie, " + cookieName);


Setting and retrieving cookies to make your website visitors feel welcome is a widely used practice on the web, therefore it's a great new skill to add to your JavaScript toolbox.

Our next useful JavaScript task is how to make sure your website visitors submit a validly filled out form. This is the topic of our next lesson: form validation.

Related topics in the RepliesViews
No related topics yet

+ Post a new topic

<< Lesson 14: JavaScript Living Space - the Browser Environment

Lesson 16: Useful Tasks (II) – Form Validation >>