Web Storage is a new HTML5 API offering important benefits over traditional cookies. Although the specification is still in W3C draft status, all major browsers support it already.
Web Storage picks up where cookies left off. The strength of Web Storage is in at least two things.
First, ease of use for web developers: It has a simple API to get and set key/value pairs
Secondly, the amount of space it provides: the specs default the disk space quota decision to the web browser usually 5 or 10 MB to be stored per domain.
There are two new objects for storing data on the client:
- localStorage - stores data with no expiration date
- sessionStorage - stores data for one session
sessionStorage.setItem('myKey', 'myValue'); var myVar = sessionStorage.getItem('myKey'); localStorage.setItem('myKey', 'myValue'); var myVar = localStorage.getItem('myKey');
Note that the interface for creating
localStorageis identical and that they are global objects.
You can use the
.setItemmethod to set the key and its value, and then
.getItemto retrieve the value of a specific key.
Note that we can only store strings, which is a significant drawback. However, to get around this, we can store and retrieve string representations of JSON objects by using the
JSON.stringify()method to store a string, and
JSON.parse()to create the original object from that string.