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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

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:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint