JavaScript code to store data as JSON strings in cookies. It uses prototype.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)
1 2 3 4 5 6 7 8 9 10 11 12 13 | jar = new CookieJar({ expires:3600, // seconds path: '/' }); dog = {name: 'Jacky', breed: 'Alsatian', age:5}; jar.put('mydog', dog); mydog = jar.get('mydog'); alert("My dog's name is " + mydog.name); alert("He is " + mydog.age + " years old"); alert("He is an " + mydog.breed); |
Download
You can view the source code here.
This code is released under CC Attribution-ShareAlike 2.5
This code is released under Apache Software License.
API
CookieJar(options)
Constructor. Takes in a object as options.
1 2 3 4 5 6 | 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 particular 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.5 (26-Jan-09)
- Changed the License to Apache Software License 2.0
v 0.4 (11-Aug-07)
- Removed a extra comma in options (was breaking in IE and Opera). (Thanks Jason)
- Removed the parameter name from the initialize function
- Changed the way expires date was being calculated. (Thanks David)
v 0.3 (22-Jun-07)
- Removed dependancy on json.js (http://www.json.org/json.js)
- empty() function only deletes the cookies set by CookieJar. Leaves alone other cookies like session_id etc.
v 0.2 (12-Apr-07)
- Released for public use.

Very nice.
Could you please submit this to http://scripteka.com
Thanks.
@kangax:
I already have
Thanks!
Hi Lalit, thank for you script. Very nice and clean.
Very slick piece of code – I’m developing a couple of applications at the moment where I’m using this – it’s a really clean and well thought out implementation – thanks for sharing it!
Does this support arrays in a json string? I keep getting errors when trying to implement an array in the object.
eg. It stores the following without a problem:
jar.put(‘test’,{‘alpha’:[{'name':'one'},{'name':'two'},{'name','three'}]})
but when I try to get it (eg. test = jar.get(‘test’)), it always returns a string and not an object. So I can’t get the value of test.alpha[0].name.
Am I doing something wrong?
Correction:
jar.put(’test’,{’alpha’:[{’name’:'one’},{’name’:'two’},{’name’:'three’}]})
(but still having problems with it).
Raj, you need to pass the array as a JS object to the function, it will automatically convert it to JSON; and when you do get, it will convert it back to object. You need not pass a JSON encoded string.
Raj,
2nd post should work. I will test and get back to you.
Hi Lalit, it seems I was suffering the “invalid label” problem (http://willcode4beer.com/tips.jsp?set=jsonInvalidLabel).
It works a treat now! Thanks!
It’s very nice.I like it.
LOVE this, thank you! doesn’t seem to work in IE6 tho. But I’m using prototype v1.6 – has there been any update? (does not work in IE7 either)
It was my fault this was not working under IE. >_< Sorry for the mis-information.
Hi, I’m trying to erase the entire cookie, but I cant. You could check my code?
That created the cookie:
And with that, in a function, I try to delete the cookie:
Your script its GREAT!!!
Pingback: 70+ JavaScript Resources for Every Web Developer
Pingback: 70+ JavaScript Resources for Every Web Developer « Battilani’s Weblog
Awesome script.
A problem with cookies -that your jar doesnt fix- is, that when you put() you have to reload the entire page before you get() the same value.
I changed so it now keeps track of what you put(), your cookie jar now always returns the value of the cookie as it should be, not how it was before you started changing things.
I did this by using your getPack() function and rewriting the get() method. The original get() is now raw(), and this is my new get:
get: function(name) {
value = this.tempJar[ name ];
if ( value )
return value;
else
return null;
},
You might want to make this as a default functionality. For others; note; you need to make more changes for this to work. One of them is placing
this.tempJar = this.getPack();
in the initialize() method at the end.
Oh, and there is a bug in the cookie_expiration date. getTime() returns time elapesed in miniseconds, not in seconds. This si the correct code:
date = new Date( ( parseInt( date.getTime() / 1000 ) ) + (this.options.expires ) );
Nifty piece of code m8!
Thanks.
Hello! great script. how do i set the cookie to never expire?
This is great!
But, I am most likely missing something (i am new to prototype and OO Javascript), but how do I retrieve a cookie, add a new field to it and return it.
So if I had a cookie that contained {item1:”data1″, item2:”data2″}
and I wanted to add {item3:”data3″}
So when I next retrieved the cookie it would give me {item1:”data1″, item2:”data2″, item3:”data3″}
Hi. Nice script. would be nice if we could just access the properties directly and then there was a save / load function.
Can you tell us some rough maximum cookie sizes in your little documentation?
Thanks
Pingback: eTools for you » Blog Archive » 70+ Sumber JavaScript
Nice script! Got 2 comments:
When enabling the secure option on a non-https connection, the cookie values will be lost. I changed this line of code to make it work:
if (this.options.secure == ‘secure’ && (“https:” == document.location.protocol)) {..
Besides this, when storing a boolean as javascript boolean, and then retrieve it, it results in a string (“true”). This is not really convenient because you have to typecast it.
Thanks anyway, great script.
Pingback: 70 melhores sites sobre Javascript
Is great, very good.
Pingback: Yet Some More Excellent JavaScript Libraries And Tools | Jeez Tech
Pingback: Cookies on Roids | El Blog del Antonio
Pingback: 70+ JavaScript Resources for Every Web Developer. | Puydi Publicidad 100% efectiva
Pingback: Comprehensive List of JavaScript Libraries « deCode10 – trends, technologies & more …
Can’t get the empty() method to work, more examples would be nice, or at least one example of each method).
document.cookie.match(name + ‘=(.*?)(;|$)’) in get function returns null in ie7 and ie8 — it works perfectly with FF
Pingback: Javascript: 66 Javascript Libraries | Skilled Monster
Pingback: JavaScript Tools Libraries List | jQuery4u
hey, i need to insert another set to json object, for example
(color: ‘black’) to
dog = {name: ‘Jacky’, breed: ‘Alsatian’, age:5};
is it possible??
Yes it is possible. You and store any object to the cookie and retrieve it back.
Pingback: 70+ JavaScript Resources for Every Web Developer | My quotes and sharings about Programming