Forum Moderators: open
// Get data if it's already been saved
// variable "saveName" is created on the parent page
var comment;
if (typeof(Storage) !== 'undefined')
comment = localStorage.getItem(saveName);
else
// getCookie is a function I wrote several years ago
comment = getCookie(saveName);
if (comment) {
// #comment is the contenteditable; if the browser doesn't support it then
// #commentText is a textarea backup
if ($('#comment').length)
$('#comment').html(comment);
else
$('#commentText').val(comment);
}
setInterval(function() {
var commentVal;
if ($('#comment').html())
commentVal = $('#comment').html();
else if ($('#commentText').val())
commentVal = $('#commentText').val();
if (commentVal) {
if (typeof(Storage) !== 'undefined')
localStorage.setItem(saveName, commentVal);
else
// setCookie is another function that I wrote a long time ago;
// the "1" sets it for 1 day
setCookie(saveName, commentVal, 1);
// #saved is on the parent page, just a DIV that says "Saved" and
// is set to style="display: none" by default
$('#saved').show()
.delay(750)
.fadeOut(1500);
}
}, 5000); var object = {comment: comment, timestamp: new Date().getTime()};
localStorage.setItem(saveName, JSON.stringify(object)); var comment, commentVal;
// Check for saved data
if (typeof(Storage) !== 'undefined') {
var getObj = JSON.parse(localStorage.getItem(saveName));
// +1 is for 1 day, you can change this to whatever you want in days
var now = new Date().getDate() + 1;
if (getObj && getObj.timestamp <= now) comment = getObj.comment;
else localStorage.removeItem(saveName);
}
else
comment = getCookie(saveName);
if (comment) {
$('#comment').html(comment);
$('#commentText').val(comment);
}
// Save data every 5 seconds; change 5000 to whatever you want
setInterval(function() {
if ($('#comment').html())
commentVal = $('#comment').html();
else if ($('#commentText').val())
commentVal = $('#commentText').val();
if (commentVal) {
if (typeof(Storage) !== 'undefined') {
var setObj = {comment: commentVal, timestamp: new Date().getDate()};
localStorage.setItem(saveName, JSON.stringify(setObj));
}
else
setCookie(saveName, commentVal, 1);
$('#saved').show()
.delay(750)
.fadeOut(1500);
}
}, 5000); To keep it short, here's the only situation in which you should use local storage: when you need to store some publicly available information that is not at all sensitive, doesn't need to be used in a high-performance app, isn't larger than 5MB, and consists of purely string data.
More specific to your question, you can use SessionStorage which is similar to LocalStorage but the stored data is automatically deleted when the browser tab is closed, thus there will be no need for expiration.