One of the specifications in the mix with HTML5 defines a new API to allow web authors to save data to the client, either for the duration of a session, or to persist after the window shuts. The official spec is available here, or there’s a more friendly example of how to use the localStorage API from Mozilla here.
I’ve just implemented this for a script based visual design tool which had a requirement to save drafts and work in progress to load back up at a later date. To achieve this, I’m using the localStorage object which is available from the window object like so…
function saveButtonClick(event) {
event.preventDefault();
var data = $('#xmlData').val();
var key = $('#saveName').val();
localStorage.setItem(key, data);
alert("Saved!");
}
To enumerate the items that have been saved to local storage, to present these in a load action panel, I’m doing the following…
function refreshSavedDesignList() {
$('#load ul').remove();
var $list = $('<ul />').appendTo($('#load div'));
for (var i = 0; i < localStorage.length; i++) {
$('<li />')
.append($('<span />').text(localStorage[i]))
.append($('<a />').attr('href', '#').text('Load').click(loadDesignClick))
.append($('<a />').attr('href', '#').text('Delete').click(deleteDesignClick))
.appendTo($list);
}
$('#load div').append($list);
}
The key parts here are using localStorage.length to identify the number of items available and localStorage[index] to get the key stored against a particular item. This is a little simplistic, as it makes the assumption that everything available in local storage is a valid saved design.
To actually read data back out, I’m doing the following…
function loadDesignClick(event) {
event.preventDefault();
var key = $(this).parents('li').find('span').text();
var data = localStorage.getItem(key);
loadDomFromXml(data);
}
In addition to calling getItem(key), setItem(key, value) and removeItem(key), you can simply add properties directly like localStorage.foo = ‘bar’.
This spec is aiming to take web applications one step closer to the behaviour of native applications which can work offline – for example, email clients cache folders locally, calendars store events locally etc. The storage APIs form one part of this, along with a proposal for a client-side SQL database, and support around instructions for offline caching of pages and dependent resources.
A full description of the offline features is available here in the W3C spec.
