opensoul.org

Making cookies with Javascript

new Cookie({eggs: 1, flour: 3, sugar: 1.5, brownSugar: 1});

Oh, wait…not those kind of cookies (mmm, now I’m hungry for cookies).

The script.aculo.us wiki has some “code for working with cookies in JavaScript”:":http://wiki.script.aculo.us/scriptaculous/show/Cookie. I’ve extended it a bit to allow for other options when setting the cookies. Here’s how to use it:

// setting cookies
Cookie.set('name', 'value');

// change domain, path, and expiration in # of days
Cookie.set('name', 'value', {
  domain: 'foobar.com',
  path: '/path',
  expires: 14
});

// the google cookie (doesn't expire)
Cookie.set('name', 'google', {expires: false});

// reading cookies
Cookie.get('name');

// Get an array all cookies that are set
Cookie.all();

// erase a cookie
Cookie.erase('name');

// check if browser accepts cookies
if(Cookie.accept()) {
  // do stuff with cookies
}

You can grab the code from here.

collectiveidea, cookies, javascript, and prototype July 11, 2007

1 Comment

  1. Nick Nick October 23, 2008

    Fab. Just what I’ve been looking for.

    You might be interested to read the “Attention developers: Your SESSIONIDs are showing” article by Jeff Williams [http://www.theregister.co.uk/2008/09/29/sessionid_protection/], specifically Page 2, where he mentions the HttpOnly attribute, and how it can be used to prevent malicious use of cookies in XSS attacks..

    granted HttpOnly isn’t part of RFC 2109, it’s an MSIE extension [http://msdn.microsoft.com/en-us/library/ms533046.aspx], but it is supported by Mozilla [https://bugzilla.mozilla.org/show_bug.cgi?id=178993]

    Nick

Post a Comment

Comments use textile. Anonymous comments will be deleted.

My name is Brandon Keepers. I like to build things, usually in Ruby or JavaScript. I work at GitHub and live in Holland, MI.

Popular Posts