cookielib.js

/* Small JavaScript cookie function library
 * Functions defined:
 *   setCookie(sName:string, sValue:string [, iExpire:int]) set session cookie named sName to value  sValue
 *      optional argument iExpire = expiration period in seconds if omitted, creates
 *      a session cookie (no expiration date; expires when browser closes)
 *   getCookie(sName:string):string return value of cookie named sName
 *   delCookie(sName:string) delete cookie named sName
 *
 * Adapted from https://msdn.microsoft.com/en-us/library/ms533693%28v=vs.85%29.aspx
 */


// Create a cookie with the specified name and value.
function setCookie(sName, sValue, iExpire)
{
  var expiration = "";
  if( iExpire !== undefined ) {
    var expireDate = new Date();
    expireDate.setTime(expireDate.getTime()+iExpire*1000); // milliseconds to seconds
    expiration = "; expires=" + expireDate.toUTCString(); 
  }
  document.cookie = sName + "=" + encodeURIComponent(sValue) + expiration;
}

// Retrieve the value of the cookie with the specified name.
function getCookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
      return decodeURIComponent(aCrumb[1]);
  }
  // a cookie with the requested name does not exist
  return null;
}

// Delete the cookie with the specified name.
function delCookie(sName)
{
  document.cookie = sName + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}