Home > Articles

📄 Contents

  1. What Is a Cookie?
  2. Setting Cookie Data
Like this article? We recommend

Like this article? We recommend

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020