Home / code / javascript

Cookies in Javascript

Cookies are small textfiles that are stored on the client computer by the server. Because HyperText Transport Protocol (HTTP) is a stateless protocol cookies provide a way to maintain information between client requests.

Netscape browsers have a file named cookies.txt where there store all cookies, Internet explorer has a directory cookies in the windows directory (win95, 98, Me) or in the Documents and Settings/user directory.

Each cookie is a small item of information with an optional expiration date.

name=value;expires=expDate;

name is the name of the data being stored and value is the value being stored. If name and value contain any semicolon, comma or blank (space) characters you must use the escape function to unescape function to decode them.

expDate is the expiration data, in GMT date format:

Wdy, DD-Mon-YY HH:MM:SS GMT

Although it's slightly different from this format, the date string returned by Date method toGMTString can be used to set cookie expiration dates.

The expiration date is an optional parameter indicating how long to maintain the cookie. If expDate is not specified, the cookie expires when the user exits the current browser session. Browsers maintains and retrieves a cookie only if its expiration date has not yet been passed.

Limitations

Cookies have these limitations

  • 4 Kbytes per cookie, for the sum of both the cookie's name and value.
  • 20 cookies per server of domain
  • Netscape can only hold 300 cookies in its cookie file.

Cookies can be associated with one or more directories. If your files are all in one directory, you don't need to worry about this. If your files are in multiple directories, you may need to use an additional path parameter for each cookie.

Using cookies with JavaScript

The document.cookie property is a string that contains all the names and values of browser cookies. You can use this property to work with cookies and JavaScript.

Here are some basic things you can do with cookies:

  • Set a cookie value, optionally specifying an expiration date.
  • Get a cookie value, given the cookie name.

It is convenient to define functions to perform these tasks. Here, for example, is a function that sets cookie values and expiration:

// set cookie values. Expiration date is optional

function setCookie(name, value, expire)
{
  document.cookie = name + "=" + escape(value)
	+ ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
}

Notice the use of escape to encode special characters (semicolons, commas, spaces) in the value string. This function assumes that cookie names do not have many special characters.

The following function returns a cookie value, given the name of the cookie:

function getCookie(Name)
{
  var search = Name + "="
  if (document.cookie.length > 0) //if there are any cookies
  {
	offset = document.cookie.indexOf (search)
	if (offset != -1) //if cookie exists
	{
	  offset += search.length
		//set index of beginning of value
	  end = document.cookie.idexOf
		//set index of end of cookie value
	  if (end == -1)
		end = document.cookie.length
	  return unescape(document.cookie.substring(offset, end))
	}
  }
}

Notice the use of unescape to decode special characters in the cookie value.

Using Cookies: an Example

Using the cookies functions defined in the previous section, you can create a simple page users can fill in to "register" when they visit your page. If they return to your pagewithin a year they will see a personal greeting.

You need to define one additional function in the HEAD of the document. This function register, creates a cookie with the name TheCoolJavaScriptPage and the value passed to it as an argument.

function register(name)
{
  var today = new Date()
  var expires = new Date()
  expires.setime(toay.getTime() +1000*60*60*24*365
  setCookie("TheCoolJavaScriptPage", name, expires)
}

The BODY of the document uses getCookie to check whether the cookie for TheCoolJavaScriptPage exists and displays a greeting if it does. Then there is a form that calls register to add a cookie. The onClick event handler also calls history.go(0) to redraw the page.

<BODY>
<H1>Register your name</H1>
<P>
<SCRIPT>
var yourname = getCookie("TheCoolJavaScriptPage")
if (yourname != null)
  document.write("<P>Welcome Back, ", yourname)
else
  document.write("<P>You haven't been here in the last year...")
</SCRIPT>

<P>Enter your name. When you return to this page within a year, you will be greeted  with a personal message.
<BR>
<FORM onSubmit="return false">
Enter your name: <INPUT TYPE="text" NAME="username" SIZE=10><BR>
<INPUT TYPE="button" value="Register"
   onClick="register(this.form.username.value); history.go(0)">
</FORM>

 

TOP