Shlomo
Shlomo

Reputation: 3990

Pure Javascript - store object in cookie

No jQuery.

I want to store an object or array in a cookie.

The object should be usable after page refresh.

How do I do that with pure JavaScript? I read many posts, but do not know how to serialize appropriately.


EDIT: Code:

var instances = {};
...
instances[strInstanceId] = { container: oContainer };
...
instances[strInstanceId].plugin = oPlugin;
...
JSON.stringify(instances); 
// throws error 'TypeError: Converting circular structure to JSON'
  1. How do I serialize instances?

  2. How do I maintain functionality, but change structure of instance to be able to serialize with stringify?

Upvotes: 47

Views: 117858

Answers (5)

Greggory Wiley
Greggory Wiley

Reputation: 981

Elaborating on @Clément Andraud answer. You can JSON.stringify a JS object and store it as a cookie. Later you can access that cookie and convert it back to a JS object.

var a = new Date(Date.now() + 1000 * 60 * 60 * 24 * 2);//2 days

Object ={
    "utm_medium": "Medium",
    "utm_campaign": "Name of something",
    "utm_id": "Id",
    "utm_content": "content",
    "utm_source": "tlchatt.com"
}
document.cookie = 'CookeName=' + JSON.stringify(paramsObjectArray) +';  path=/; expires=' + a.toGMTString() + ';' 

Upvotes: 0

Jean-Robin Tremblay
Jean-Robin Tremblay

Reputation: 119

A cookie adaptation class from : http://www.sitepoint.com/cookieless-javascript-session-variables/

All you need to do is to set and get variables you need to store in cookie.

Work with: int, string, array, list, Complex object

Exemple:

var toStore =  Session.get('toStore');

if (toStore == undefined)
    toStore = ['var','var','var','var'];
else
    console.log('Restored from cookies'+toStore);

Session.set('toStore', toStore);

Class:

// Cross reload saving
if (JSON && JSON.stringify && JSON.parse) var Session = Session || (function() {
// session store

var store = load();

function load()
{
    var name = "store";
    var result = document.cookie.match(new RegExp(name + '=([^;]+)'));

    if (result)
        return JSON.parse(result[1]);

    return {};
}

function Save() {
    var date = new Date();
    date.setHours(23,59,59,999);
    var expires = "expires=" + date.toGMTString();
    document.cookie = "store="+JSON.stringify(store)+"; "+expires;
};

// page unload event
if (window.addEventListener) window.addEventListener("unload", Save, false);
else if (window.attachEvent) window.attachEvent("onunload", Save);
else window.onunload = Save;

// public methods
return {

    // set a session variable
    set: function(name, value) {
        store[name] = value;
    },

    // get a session value
    get: function(name) {
        return (store[name] ? store[name] : undefined);
    },

    // clear session
    clear: function() { store = {}; }
};
})();

Upvotes: 6

Beat Richartz
Beat Richartz

Reputation: 9622

Try that one to write

function bake_cookie(name, value) {
  var cookie = [name, '=', JSON.stringify(value), '; domain=.', window.location.host.toString(), '; path=/;'].join('');
  document.cookie = cookie;
}

To read it take:

function read_cookie(name) {
 var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
 result && (result = JSON.parse(result[1]));
 return result;
}

To delete it take:

function delete_cookie(name) {
  document.cookie = [name, '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.', window.location.host.toString()].join('');
}

To serialize complex objects / instances, why not write a data dump function in your instance:

function userConstructor(name, street, city) {
   // ... your code
   this.dumpData = function() {
     return {
        'userConstructorUser': {
            name: this.name,
            street: this.street,
            city: this.city
         }
       }
    }

Then you dump the data, stringify it, write it to the cookie, and next time you want to use it just go:

  var mydata = JSON.parse(read_cookie('myinstances'));
  new userConstructor(mydata.name, mydata.street, mydata.city);

Upvotes: 84

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22481

Use either object's own .toString() method if it gives meaningful serialization or JSON.stringify(). Do note, however, that cookies are usually limited in length and won't be able to hold big amounts of data.

Upvotes: 6

Clément Andraud
Clément Andraud

Reputation: 9279

If you can serialize your object into its canonical string representation, and can unserialize it back into its object form from said string representation, then yes you can put it into a cookie.

Upvotes: 6

Related Questions