Javascript Read and Write Multiple values in a Cookie

Javascript Best Practices

Best method of reading and writing mutliple values to a cookie with Javascript.


Date : 2006-05-08
When dealing with cookies many people expect them to act just like variables but this is not the case. Cookies have many restrictions due to security and other considerations. These days with most people running some kind of internet security software and browsers incorporating more and more security checks it is more important than ever to make sure that we handle cookies as delicately as possible. One way to do this is by placing all of your values in one cookie instead of trying to place multiple cookies. The functions below will help you do just that.

I adapted one of these from a book on javascript and I made the other one myself. I added the option of picking your own delimiter for multiple cookie variables because sometimes you may want to save text that has a common delimiter, or you may want to make a 3 demensional array in a cookie by changing the delimiter.

So here are the functions:

Code:
function readCookie(name,delimit)
{
  if (document.cookie == '')
  {
    return false;
  }
  else
  {
    var fC,lC;
    var mcookie = unescape(document.cookie);
    fC = mcookie.indexOf(name);
    var ph = fC + name.length;
    if ((fC != -1) && (mcookie.charAt(ph) == '='))
    {
      fC += name.length + 1;
      lC = mcookie.indexOf(delimit,fC);
      if (lC == -1) lC = mcookie.length;
      return unescape(mcookie.substring(fC,lC));
    }
    else
    {
      return false;
    }
  }
}


function returns false if there was no cookie found with that name.

Here is the write cookie function. It's a little more complicated.

Code:
function writeCookie(name,value,delimit)
{
  if (document.cookie == '')
  {
    document.cookie = escape( name + "=" + value );
    return false;
  }
  else
  {
    var B4,Af,fC,lC;
    var mcookie = unescape(document.cookie);
    var ncookie;
    fC = mcookie.indexOf(name);
    var ph = fC + name.length;
    if ((fC != -1) && (mcookie.charAt(ph) == '='))
    {
      B4 = mcookie.substring(0,fC);
      fC += name.length + 1;
      lC = mcookie.indexOf(delimit,fC);
      if (lC == -1) lC = mcookie.length;
      if (lC == mcookie.length)
      {
        ncookie = B4 + name + "=" + value;
        document.cookie = escape(ncookie);
        return true;
      }
      else
      {   
        Af = mcookie.substring(lC,mcookie.length);
        ncookie = B4 + name + "=" + value + Af;
        document.cookie = escape(ncookie);
        return true;
      }   
    }
    else
    {
      ncookie = mcookie + delimit + name + "=" + value;
      document.cookie = escape(ncookie);
      return false;
    }
  }
}   

The writeCookie function returns true if the action was successful and false if not.

I hope these prove usefull to you.
If anyone has improvements on these scripts please leave a comment.

Comments :

No comments yet
  • Search For Articles