Reputation: 954
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:
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
Upvotes: 5
Views: 16189
Reputation: 221
I would recommend not to use cookies to store the type of data you are using, as cookies are basically meant to store very small amount of data like some key, id...
You can use local storage instead as the local storage limit is 5 MB that too is extensible.Also local storage is much more secure than cookies as the data is not being sent to server.
Upvotes: 2
Reputation: 5213
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;
})()
Upvotes: 5
Reputation: 1697
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));
Upvotes: 5
Reputation: 2861
You can store ONLY STRINGS. A very limited type of strings. You need to use some separators to store such values. Look at Allowed characters in cookies which ones you can use.
Upvotes: -1