Using JavaScript Cookies with HTML

Exploring Ways to Read, Write, Delete and Manipulate document.cookie

© Guy Lecky-Thompson

Jun 19, 2008
JavaScript tutorial how-to article class notes for managing document.cookie objects using the JavaScript cookie functions, as well as the date object, and string.split.

Compute cookies are little pieces of textual information that are attached to a website, or page. One use for cookies is as session cookies - security measures based around giving the browser a cookie after login, which can then be validated before actions are performed. As long as the user logs out, or the cookie becomes invalid, subsequent users on the same, or a different, machine will not be able to access the users account.

Cookies are usually manipulated with a scripting language like JavaScript (client) or PHP (server). This article deals with:

  • Cookie storage
  • Reading cookies
  • Writing cookies
  • Setting / deleting cookies

One point to note is that cookies are protected by the browser security mechanism, which means that cookies can not be shared across web sites - a page in one (sub)domain can not usually access cookies from another domain. However, since they are just pieces of text, they can be read, by the user, with a simple text editor.

Where Are Cookies Stored?

Physically, cookies are stored in a location known only to the browser, although for the main browser platforms, these locations are well-known. Logically, a cookie belongs to a domain and a path. When the JavaScript set cookies process is invoked, the script either presents the browser with a domain, or a blank value. If no domain is given it is assumed to be the domain of the page i.e. java-programming.suite101.com in this case.

The JavaScript cookies path, on the other hand, allows the programmer to make sure that the cookie is only valid (sent to the server) for pages in a specific path on the website.

So, specifying a path such as /blog would restrict the cookie to my.domain.com/blog. If the cookie should be applicable across the whole (sub)domain, then path=/ should be specified.

(Cookies can be shared across subdomains by specifying only the main domain, i.e. suite101.com allows access from www.suite101.com as well as computerprogramming.suite101.com)

How To Use Cookies

Cookies are set and retrieved through the HTML DOM document.cookie object, which returns a string value. In the string there are name-value pairs which represent the cookies stored for the domain and path. No domain, path, or expiration information is returned by the document.cookie object, although the JavaScript 'set cookies' process does require that this information is given.

Once a cookie has expired, the value is lost, and is not returned in the document.cookie string. It is very simple to use JavaScript to write cookies to the browser cookie database. It is simply a case of building up a string, and assigning it to the document.cookie object. The cookie string takes the following form:

'cookie_name=cookie_value; expires=<date in string format>path =/'
i.e. : 'number_of_visits=1; expires=Mon, 30 Jun 2008 00:00:00 UTC; path=/cgi-bi'

To create a cookie with a certain expiration date, it is necessary to create an appropriate JavaScript Date Object, and then use the toString function to convert it to the correct string (see Using the JavaScript Date Object for more information). The code to build the date (for 1 day in the future) and set the cookie, is as follows:

var expirationDate = new Date();
expirationDate.setTime(date.getTime()+(24*60*60*1000)); // in milliseconds!
var expirationString = "; expires="+expirationDate.toGMTString();
document.cookie = cookieName+"="cookieValue+expirationString+"; path="cookiePath;

Of course, the cookieName, cookieValue, and cookiePath strings must also be built up before the code is executed. Once the cookie is set, it can be read back.

How To Read Cookies

To use JavaScript to read cookies, all that is required is to retrieve the string from document.cookie. It is structured as follows:

cookie_name=cookie_value; cookie_name_2=cookie_value_2

In order to correctly parse it, it is necessary to use the JavaScript string.split to generate an array of name value pairs, and then split each one into name and value strings. For more information about manipulating strings and arrays, please see the JavaScript Split List or String article. Sample code might be:

var nameValueList = document.cookie.split(';');
for ( item = 0; item < nameValueList.length; item++) {
var nameValue = nameValueList[item].split('=');
// nameValue[0] == name
// nameValue[1] == value
}

These cookies can also be passed back to the server, and used, for example, as PHP session cookies, or for providing personalized information to visitors.


The copyright of the article Using JavaScript Cookies with HTML in Javascript/Java Programming is owned by Guy Lecky-Thompson. Permission to republish Using JavaScript Cookies with HTML in print or online must be granted by the author in writing.




Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo