Yummy JSON Cookies (using Prototype)

Updated to v.3: CookieJar now uses only prototype.js 1.5.1. See changes

JavaScript code to store data as JSON strings in cookies. It uses prototype.js 1.5.1 and json.js to store and retrieve JSON data from cookies.

Now we can store and retrieve JavaScript Objects, Arrays, Boolean, String, Number values using cookies, just like storing Java Objects in session on the server side.

Works with Firefox 1.5, 2.0, IE 6.0 and Opera 9.10.


Example   (Execute this example!)


Source

You can view the source code here.
Please report bugs and suggestions here.
This code is released under CC Attribution-ShareAlike 2.5.


API

CookieJar(options)
Constructor. Takes in a object as options.

options = {
  expires: '',  // time in seconds (defualt: 3600)
  path: '',     // cookie path
  domain: '',   // cookie domain
  secure: ''    // secure ?
};

boolean put(string name, mixed value)
Puts a particular cookie in the cookie jar. The cookie is associated with the name. Returns false if cannot add cookie (Ex: max cookie size exceeded!). Returns true on success.

mixed get(string name)
Gets a particular cookie from the cookie jar. Returns null if not found.

boolean remove(string name)
Removes a particualr cookie from the cookie jar. Returns true on success, false otherwise.

void empty()
Empties the Cookie Jar.

array getKeys()
Gets array of all the cookie names.

object getPack()
Gets all the cookies as a single JavaScript object (Package) with name value pairs.


Change Log

v 0.4 (11-Aug-07)

  1. Removed a extra comma in options (was breaking in IE and Opera). (Thanks Jason)
  2. Removed the parameter name from the initialize function
  3. Changed the way expires date was being calculated. (Thanks David)

v 0.3 (22-Jun-07)
  1. Removed dependancy on json.js (http://www.json.org/json.js)
  2. empty() function only deletes the cookies set by CookieJar. Leaves alone other cookies like session_id etc.

v 0.2 (12-Apr-07)
  1. Released for public use.


Page last updated: 22-Jun-07
 

lalit.org  ›  blog | inspiration | lab | synapsys | who? | bio | email