Home > Articles

📄 Contents

  1. What Is a Cookie?
  2. Setting Cookie Data
  • Print
  • + Share This
From the author of

Setting Cookie Data

You set, get, and delete cookie data by working with the Document object's cookie property. Remember, however, that cookie data is in no way tied to an individual document. Instead, you can work with your cookie data from within any document on your site (although there are some limitations on this; see "Specifying the Path," later in this article).

To set a cookie, you assign a specially formatted string to the cookie property:

document.cookie = Cookie_String

Cookie_String

A string that contains the cookie data in the form of name/value pairs separated by semicolons


These "name/value pairs" specify different aspects of the cookie. The next four sections introduce you to all the possible name/value pairs.

The Simplest Case: Setting the Cookie Name and Value

The most basic cookie contains only the cookie name and its value. Here's the general syntax:

document.cookie = "Cookie_Name=Cookie_Value"

Cookie_Name

The name of the cookie

Cookie_Value

The value of the cookie


CAUTION

Don't use semicolons (;), commas (,), or spaces in either the cookie name or the cookie value.

For example, if you want to store a cookie named user_first and the value Paul, you'd use the following statement:

document.cookie = "user_first=Paul"

Suppose, instead, that you wanted to save a cookie named book_name and the value Special Edition Using JavaScript. The value contains three spaces, so how do you get around that? The easiest way is to use the escape() method (JavaScript 1.0). This method takes a string argument and converts any character that isn't a letter or a number into its numeric (hexadecimal) equivalent, preceded by the percent sign (%). Here's the syntax:

escape(String_Value)

String_Value

The string you want to convert


For example, the hexadecimal equivalent for a space is 20, so the expression escape("Special Edition Using JavaScript") would return the following:

Special%20Edition%20Using%20JavaScript

So, the cookie statement would look like this:

document.cookie = "book_name=" + escape("Special Edition Using JavaScript")

Getting the Cookie Value

Retrieving the value of a cookie takes a bit more work. You begin by storing the cookie property in a variable:

cookie_string = document.cookie

This will return a string in the following format:

Cookie_Name=Cookie_Value

There are a number of ways to extract the Cookie_Value part. One method is to first locate the index position of the equals sign:

equals_location = cookie_string.indexOf("=")

Given that, you can then use the String object's substring() method to extract the value:

cookie_value = cookie_string.substring(equals_location + 1)

If the value was encoded using the escape() method, then you need to decode it using the unescape() method (JavaScript 1.0):

unescape(String_Value)

String_Value

The string you want to decode


Here's the revised statement that gets the cookie:

cookie_string = unescape(document.cookie)

Let's try a simple example that tracks the number of times a user has visited a site. Listing 1 holds the code.

Listing 1: Getting and Setting a Simple Cookie

<script language="JavaScript" type="text/javascript">
<!--

// This function retrieves the cookie value
function get_cookie() {
  cookie_string = unescape(document.cookie)
  equals_location = cookie_string.indexOf("=")
  cookie_value = cookie_string.substring(equals_location + 1)
  return cookie_value
}

// Get the cookie
var visit_number = get_cookie()

// Did the cookie exist?
if (!visit_number) {

  // If not, then this is the user's first visit
  visit_number = 1
  document.writeln("This is your first visit.")
}
else {

  // Otherwise, increment the visit number
  visit_number++
  document.writeln("This is visit number " + visit_number + ".")
}

// Set the cookie
document.cookie="count_cookie=" + visit_number

//-->
</script>

NOTE

All the code listings in this article are available online from my Web site, http://www.mcfedries.com/UsingJavaScript/.

The script begins with a function named get_cookie() that handles the dirty work of retrieving, extracting, and returning the cookie value. After that, the script runs get_cookie() and stores the returned value in the visit_number variable. Then an if() statement checks the value of visit_number. If it's null, the cookie didn't exist, which means this is the user's first visit to the site. In this case, visit_number is set to 1 and an appropriate message is written to the document. Otherwise, visit_number is incremented and the new value is written to the page. Finally, the cookie value is updated with the new value of visit_number.

Adding an Expiration Date

The cookies you've worked with so far are known in the trade as per-session cookies because they last only as long as the user's browser session. If she quits her browser, these cookies are destroyed and they'll start from scratch the next time she visits your site.

If you want to preserve data from one browser session to the next, you have to create what are known as persistent cookies. To do that, you have to expand the saved cookie data to include an expiration date. Here's the general syntax:

document.cookie = "Name=Value; expires=GMT_String"

Name

The name of the cookie

Value

The value of the cookie

GMT_String

A string that represents the GMT date the cookie will expire


The usual method for specifying the expiration date string is to set it up as a certain number of days from the current date. Here's a code snippet that demonstrates how to do this:

var expire_days = 30
var expire_date = new Date()
var ms_from_now = expire_days * 24 * 60 * 60 * 1000
expire_date.setTime(expire_date.getTime() + ms_from_now)
var expire_string = expire_date.toGMTString()

The expire_days variable holds the number of days after which the cookie will expire, and expire_date is initialized to the current date. In the third statement, expire_days is converted to milliseconds by multiplying it by 24 hours, 60 minutes, 60 seconds, and 1000 milliseconds, and the result is stored in the ms_from_now variable. Then expire_date is set to the future date using setTime(), which adds the current date (converted into milliseconds by the getTime() method) and the ms_from_now value. Finally, the result is converted to a string in the GMT format using the toGMTString() method.

To include this with the cookie, you'd use a statement such as this:

document.cookie = "count_cookie=visit_number; expires=" + expire_string

TIP

If you want an expiration time that's less than a day, just convert the time from now into a milliseconds value, as follows:

hours—Multiple the number of hours by 60 * 60 * 1000 (minutes times seconds times milliseconds).

minutes—Multiple the number of minutes by 60 * 1000 (seconds times milliseconds).

seconds—Multiple the number of seconds by 1000 (milliseconds).

NOTE

Including the expires parameter has no effect on the string returned by the cookie property. The expiration date is stored in the cookie file, but the cookie property still returns only the cookie names and values, separated by "; ".

Specifying the Path

By default, any cookie you set is available to all the other pages in the same directory as the page that created the cookie. And if that directory has subdirectories, all the pages in those subdirectories can access the cookie as well. However, the cookie is not available to any other directory on your site.

For example, suppose your site has the following four directories:

/
/cookie_dir
/cookie_dir/cookie_sub
/other_dir

Suppose further that the page that creates the cookie is located in the /cookie_dir directory. In that case, the cookie can be accessed by any page in the /cookie_dir directory as well as any page in the /cookie_dir/cookie_sub subdirectory. The cookie can't be accessed by any page in the / (root) directory or by any page in the /other_dir directory.

To gain some control over which directories can access cookies, you need to specify the path parameter when setting the cookie. Here's the general syntax:

document.cookie = "Name=Value; path=Cookie_Dir"

Name

The name of the cookie

Value

The value of the cookie

Cookie_Dir

A string that specifies the topmost directory that can access the cookie


For example, if you want the topmost directory to be one that's named shopping, then you set the path parameter like this:

document.cookie = "name1=value1; path=/shopping"

If you want the cookie to be available to every page on your site, set the path parameter to the root (/):

document.cookie = "name1=value1; path=/"

Setting Other Cookie Data

To complete the syntax used when setting a cookie, this section looks at two more parameters: domain and secure.

The domain parameter enables you to specify which host names on your site can access a cookie. Here's the syntax:

document.cookie = "Name=Value; domain=Cookie_Domain"

Name

The name of the cookie

Value

The value of the cookie

Cookie_Domain

A string that specifies the domain name or domain specification


If you don't include the domain parameter, then the default is the host name of the Web server that hosts your site. If you have just the one host name on that server, then you never need to worry about the domain parameter.

This parameter comes in handy in situations where you have multiple host names. For example, you might have a host name of the form http://www.domain.com and another of the form commerce.domain.com. In that case, cookies that you create on the http://www.domain.com host are not available to pages on the commerce.domain.com host. To fix that, specify the string .domain.com as the domain parameter:

document.cookie = "name1=value1; domain=.domain.com"

Note the leading dot (.) before the domain name. This ensures that only your own hosts can access the cookie. If you don't include the leading dot, the cookie won't set.

The final parameter is secure, which is a Boolean value:

document.cookie = "Name=Value; Cookie_Secure"

Name

The name of the cookie.

Value

The value of the cookie.

Cookie_Secure

If this is true, then the cookie is sent only to the browser if the connection uses the HTTPS (secure) protocol; if it's false (or omitted), then the cookie is sent even if the unsecure HTTP protocol is used.


Here's an example:

document.cookie = "name1=value1; true"

Handling All the Cookie Parameters

To make it easier to handle all these cookie parameters, it's a good idea to create a function that does the work for you. I'll show you such a function in this section.

First, let's set up an example: saving the user's choice of background color. Listing 3 shows a bit of code from 25.3.htm.

Listing 3: Using a Cookie to Set the Background Color

// Get the bgColor cookie
var bg_color = get_cookie("bgColor_cookie")

// Did the cookie exist?
if (bg_color) {
  self.document.bgColor = bg_color
}

This code calls the get_cookie() function, which is the same function as the one shown earlier in Listing 2. In this case, the code wants the value of the cookie named bgColor_cookie, and the result is stored in the bg_color variable. If the cookie existed, then the document's bgColor is set to the cookie's value.

The page 25.3.htm also contains the following link:

<a href="javascript:open_window()">
Change and set the background color of this window
</a>

When clicked, this link calls the open_window() function.

This new window contains 25.4.htm, which has the code that sets the cookie named bgColor_cookie. Clicking the Change and Set the Color button runs the set_color() function, which is shown in Listing 4.

Listing 4: Using a Cookie to Save the Background Color

<script language="JavaScript" type="text/javascript">
<!--

function set_color(color_form) {

  // Get the currently selected color
  var color_list = color_form.color_name
  var selected_color = color_list.options[color_list.selectedIndex].value
  
  // Change the color of the background
  opener.document["bgColor"] = selected_color
  
  // Save it in a cookie
  set_cookie("bgColor_cookie", selected_color, 365, "/")
}

function set_cookie(cookie_name, cookie_value, cookie_expire, cookie_path, 
          cookie_domain, cookie_secure) {

  // Begin the cookie parameter string
  var cookie_string = cookie_name + "=" + cookie_value
  
  // Add the expiration date, if it was specified
  if (cookie_expire) {
    var expire_date = new Date()
    var ms_from_now = cookie_expire * 24 * 60 * 60 * 1000
    expire_date.setTime(expire_date.getTime() + ms_from_now)
    var expire_string = expire_date.toGMTString()
    cookie_string += "; expires=" + expire_string
  }
  
  // Add the path, if it was specified
  if (cookie_path) {
    cookie_string += "; path=" + cookie_path
  }

  // Add the domain, if it was specified
  if (cookie_domain) {
    cookie_string += "; domain=" + cookie_domain
  }
  
  // Add the secure Boolean, if it's true
  if (cookie_secure) {
    cookie_string += "; true"
  }
  
  // Set the cookie
  document.cookie = cookie_string

}

//-->
</script>

The set_color() function gets the current color in the list and uses it to change the original document's bgColor property. In the last line, a function named set_cookie() is called. This is a function I created for handling the cookie parameters. Here's the syntax of this function:

function set_cookie(cookie_name, cookie_value, cookie_expire, cookie_path, 
          cookie_domain, cookie_secure)

cookie_name

The name of the cookie.

cookie_value

The value of the cookie. (Remember to "escape" this value if you think it might contain spaces.)

cookie_expire

(Optional) The number of days until the cookie expires.

cookie_path

(Optional) The cookie's path parameter.

cookie_domain

(Optional) The cookie's domain parameter.

cookie_secure

(Optional) The cookie's secure parameter.


Here's an example call that uses all six arguments:

set_cookie("bgColor_cookie", selected_color, 365, "/", ".mcfedries.com", true)

The function begins by declaring a variable named cookie_string and initializing it to the cookie's name/value pair:

var cookie_string = cookie_name + "=" + cookie_value

Then a series of if() statements tests the value of four parameters. In each case, if the parameter isn't null, then the parameter name and value are concatenated to cookie_string. When that's done, the cookie is set:

document.cookie = cookie_string
  • + Share This
  • 🔖 Save To Your Account