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
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;
})()
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With