Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set object into cookie

I am developping a client side web application with jquery

I want to store all visited pages, I use cookie for it

So, I have two element to store:

  • page URL
  • page title

I start creation of data in cookie as :

Index.html :

if(!$.cookie("history")){
        var url_history = document.location;
        var title_history = $("html title").text();
        $.cookie("historyURL", url_history);
        $.cookie("historyTITLE", title_history);
    }

anotherPage.html :

var url_history = document.location;
var title_history = $("html title").text();
$.cookie("historyURL", url_history);
$.cookie("historyTITLE", title_history);

Problem is that cookie's new value overwrites the old.

I think I should set an object, not string such as:

var objHistory = [];
objHistory.push({url:document.location, title: $("html title").text()})
$.cookie("history", objHistory);

Now I have another problem:

I can't retrieve My Object from cookie

When I am trying to get my Object from cookie, It shows a string "object" not Object

Is it possible to set an object in cookie?

thank for your help

like image 939
Valeriane Avatar asked Dec 21 '22 13:12

Valeriane


2 Answers

You can always stringify your object into JSON:

var jsonHistory = JSON.stringify(objHistory);
$.cookie("history", jsonHistory);

Edit

Simple demo (tested in Chrome and Firefox):

        (function(){
            var o = JSON.parse('{"id":1,"value":"code.google.com"}');
            var e = 'Thu Nov 10 2012 15:44:38';
            document.cookie = 'myObj='+ JSON.stringify(o) +';expires=' + e;
        })()
like image 37
Alberto De Caro Avatar answered Dec 31 '22 00:12

Alberto De Caro


A cookie (having a limited 4K size) is the last place I would attempt to store an array of pages visited. A cookie would be the last storage method I'd attempt to use due to its limitations. If you are in HTML5, why are you not using the localStorage for this purpose?

Tutorial: http://www.w3schools.com/html/html5_webstorage.asp

The localStorage handles only STRING key/value pairs. A workaround can be to stringify your object before storing it, and later parse it when you retrieve it:

var testObject = { 'URL': 1, 'TITLE': 2 };
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
like image 90
sainiuc Avatar answered Dec 31 '22 01:12

sainiuc