Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 245
Shlomo Avatar asked Jul 05 '12 12:07

Shlomo


People also ask

How can I store JavaScript objects in cookies?

Store objects in the Cookies The cookies store information in the string format only. If users want to store any other types of data in the cookies, they need to convert it to the string using the stringify() method. In this section, we will convert the object to a string and store it in cookies.

Can you store JSON in cookie?

I think it's okay to store JSON in cookies, but as per curl.se/rfc/cookie_spec.html about the value: "This string is a sequence of characters excluding semi-colon, comma and white space". So you have to use something like encodeURIComponent(value) before storing the cookie.

How does JavaScript store objects?

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

Can we store object in object JavaScript?

You can't store Objects using localStorage - you can only store there strings. What you can do is convert your object to string (using JSON. stringify ) and then save it.


2 Answers

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); 
like image 183
Beat Richartz Avatar answered Oct 22 '22 02:10

Beat Richartz


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.

like image 30
Oleg V. Volkov Avatar answered Oct 22 '22 02:10

Oleg V. Volkov