February 25, 2000 - Setting the Cookie's Expiration Date | WebReference

February 25, 2000 - Setting the Cookie's Expiration Date

Yehuda Shiran February 25, 2000
Setting the Cookie's Expiration Date
Tips: February 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

The default expiration date of a cookie is the current session. If you don't set the expiration date, your cookies will expire upon exiting the browser window. Want to check it? Use the following line to set a cookie:

setCookie("docjs", 329);

and the following line to get it:

cookieTrace = getCookie("docjs");

When you try alert(cookieTrace), you get 329. Try a few more times to run the line above. You keep getting the 329 number. Now exit the browser and run the line above. You get "null".

Here are the getCookie() and setCookie() functions:

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}
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));
}

Learn more about cookies in Column 8, Crispy JavaScript Cookies.