spacer
Yehuda Shiran January 11, 2002
Getting Cookies
Tips: January 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
OpenOffice 3.2 Lands Amid Critical Changes
Red Hat, IBM Firmly in KVM Virtualization Camp
Red Hat Talks Up Open Source Cloud Plans

One way to store and retrieve data on the client side is by using cookies. The cookie property is a member of the document object. You can store thousands of cookies per client. You can get a cookie with the following getCookie() function:

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}
where name is the name of the cookie as you stored it originally. The function getCookie() returns a string containing the value of the specified cookie or null if cookie does not exist.

The cookie property includes all cookies that were set for a particular page. The requested cookie may or may not be the first one in the cookie property. The function first assembles the string to search in the cookie, assuming it is not the first one. The string is concatenated from a semicolon, the name of the cookie, and an equal sign. If, for example, the name of the cookie is "kuku", then the string to search is ";kuku=". If there is no match, the possibility of being the first on the cookie property is considered. If it is not found, a null value is returned:

    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
Once a match is found, (begin != 0), we look for the end of the string or the following semicolon, and extract the string up to it:

  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));

People who read this tip also read these tips:

Look for similar tips by subject:


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Search Engine Optimization: Selecting and Embedding Keywords · Are Google's Language Translation Web Services Ready for Prime Time? · Installing and Using Meeplace, the Business Review CMS
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
IBM DB2 10 for z/OS: Justifying the Upgrade · Living La Vida Colo: Choosing the Right Colocation Facility · FTC Concerns over Social Media Privacy Linger