Cookie Jar: Yummy JSON Cookies (using Prototype)

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)

  1. Changed the License to Apache Software License 2.0

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.

Related

• • •

36 Responses to Cookie Jar: Yummy JSON Cookies (using Prototype)

  1. kangax says:

    Very nice.
    Could you please submit this to http://scripteka.com

    Thanks.

  2. Lalit says:

    @kangax:
    I already have :)
    Thanks!

  3. Hi Lalit, thank for you script. Very nice and clean.

  4. William says:

    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!

  5. Raj Parmar says:

    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?

  6. Raj Parmar says:

    Correction:
    jar.put(’test’,{’alpha’:[{’name’:'one’},{’name’:'two’},{’name’:'three’}]})

    (but still having problems with it).

  7. Lalit says:

    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.

  8. Lalit says:

    Raj,
    2nd post should work. I will test and get back to you.

  9. Raj Parmar says:

    Hi Lalit, it seems I was suffering the “invalid label” problem (http://willcode4beer.com/tips.jsp?set=jsonInvalidLabel).

    It works a treat now! Thanks!

  10. jeff says:

    It’s very nice.I like it.

  11. scott says:

    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)

  12. scott says:

    It was my fault this was not working under IE. >_< Sorry for the mis-information.

  13. Facundo says:

    Hi, I’m trying to erase the entire cookie, but I cant. You could check my code?
    That created the cookie:

        jar = new CookieJar({expires:3600, path: '/'});
        shop = {order_id: results['order_id']};
        jar.put('shop', shop);

    And with that, in a function, I try to delete the cookie:

        jar = new CookieJar();
        if (jar.get('shop')){
            shop = jar.get('shop');
            if (shop.order_id==results['order_id']){
                jar.remove('shop');
            }
        }

    Your script its GREAT!!!

  14. Pingback: 70+ JavaScript Resources for Every Web Developer

  15. Pingback: 70+ JavaScript Resources for Every Web Developer « Battilani’s Weblog

  16. ChessSpider says:

    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.

  17. ChessSpider says:

    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 ) );

  18. pC says:

    Nifty piece of code m8!
    Thanks.

  19. pk says:

    Hello! great script. how do i set the cookie to never expire?

  20. Caleb says:

    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″}

  21. Tim says:

    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

  22. Pingback: eTools for you » Blog Archive » 70+ Sumber JavaScript

  23. Willem says:

    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.

  24. Pingback: 70 melhores sites sobre Javascript

  25. fernand says:

    Is great, very good.

  26. Pingback: Yet Some More Excellent JavaScript Libraries And Tools | Jeez Tech

  27. Pingback: Cookies on Roids | El Blog del Antonio

  28. Pingback: 70+ JavaScript Resources for Every Web Developer. | Puydi Publicidad 100% efectiva

  29. Pingback: Comprehensive List of JavaScript Libraries « deCode10 – trends, technologies & more …

  30. Justin says:

    Can’t get the empty() method to work, more examples would be nice, or at least one example of each method).

  31. Gabi says:

    document.cookie.match(name + ‘=(.*?)(;|$)’) in get function returns null in ie7 and ie8 — it works perfectly with FF

  32. Pingback: Javascript: 66 Javascript Libraries | Skilled Monster

  33. Pingback: JavaScript Tools Libraries List | jQuery4u

  34. Ashik says:

    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??

  35. Pingback: 70+ JavaScript Resources for Every Web Developer | My quotes and sharings about Programming