View Single Post
Old 03-01-2004, 07:17 PM   PM User | #3
liorean
The thread killer


 
Join Date: Feb 2003
Location: Umeå, Sweden
Posts: 5,575
Thanks: 0
Thanked 84 Times in 75 Posts
liorean will become famous soon enoughliorean will become famous soon enough
Q: How do you read, write, delete and detect support for cookies?

A: Let's take it one step at a time:
  • Reading cookies is simple. document.cookie is the JavaScript interface to cookies. It contains a semicolon separated list of cookies in the following fashion: "cookiename1=cookievalue1;...;cookienamen=cookievaluen". Only cookies for the current domain and path will be included in the string.
  • Writing cookies is more complicated. The easiest form of cookies are session-only cookies, which only lives as long as the browser window. These are written simply like this:
    Code:
    document.cookie="cookiename=cookievalue";
    Longer lived cookies are more advanced. They contain a string of the following pattern: "cookiename=cookievalue;expires=date;path=path;domain=domain;secure". Only include the path, domain and secure parts if you need to set them to something other than the default (which is '/', document.domain, and absent, respectively). date should be in the form of the return from the toUTCString method of instances of JavaScript's Date object.
  • Deleting cookies is done by overwriting a cookie, setting the expiry time in the past. Thus,
    Code:
    document.cookie='cookiename=;'+
        'expires=Thu, 01-Jan-70 00:00:01 GMT;'+
        'path=path;'+
        'domain=domain";
    where path and domain MUST be the same as they were when the cookie was originally set.
  • Detecting cookie support is done by writing a cookie and then reading it out again. If the value is the same as what you wrote, the browser supports cookies.
If you don't feel like writing your own cookies handling script, there are many cookies libraries out there that you can use. I personally wrote two different ones in this thread, for instance, and the rest of the CF community has contributed to among other places this thread.

Last edited by liorean; 03-29-2004 at 06:50 PM..
liorean is offline