January 11, 2002 - Getting Cookies | WebReference

January 11, 2002 - Getting Cookies

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

Yehuda Shiran, Ph.D.
Doc JavaScript

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));