Web Storage

Intro Articles

See Apple’s tutorial on Web Applications.

From HTML5Doctor and one from WebDirections.

Also, take a quick look at the Filesystem API.

Description

The API for localStorage and sessionStorage is exactly the same, and distills down to the following methods:

If Web Storage is working, you will see two identical columns of text below.

Another example

Clicking a checkbox will immediately save that value to the database. After closing your browser and coming back to this page, you should see your previously saved values.





.setItem(key, value);
.getItem(key)
.removeItem(key)
.clear() - empties out all contents
.key(index)
.length

Storing Data

Call the .setItem() method — for example:

if (window.sessionStorage) { //we use sessionStorage

    window.sessionStorage.setItem("fullName","Craig Creeger");

} else {

    //we do something else, perhaps use cookies, or another fallback

    //NOTE: There are a few polyfills available for IE7 and older.

}

There is also a shortcut method for calling setItem(). Simply create and set a property on the sessionStorage object. This will automatically call setItem() behind the scenes. For example:

window.sessionStorage.fullName = "Craig Creeger";

Retrieving Data

This is done in a similar manner as storing the data.

var myName = window.sessionStorage.getItem("fullName");

    or

var myName = window.sessionStorage.fullName;

If for some reason the key doesn’t exists, it will return a null. So you could do a test after the read, such as:

var myName = window.sessionStorage.fullName;
if (myName!=null) {
  //use it
} else {
  myName = "default value";
}

Delete a Key/Value Pair

window.sessionStorage.removeItem("fullName");

    or

delete window.sessionStorage.fullName;

Gotchas, Tips and Tricks

sessionStorage and localStorage store all data as strings

As mentioned earlier, the values stored in local and session storage are strings, which has a number of implications for developers.

In particular, when we store boolean values, integers, floating point numbers, dates, objects and other non-​​string values, we need to convert to and from a string when writing to and reading from storage.

There’s also a more subtle side effect of storing values as strings. JavaScript strings are UTF-​​16 encoded, which means each character is 2 bytes (in UTF-​​8 characters are one byte). This effectively halves the available storage space.

The main gotcha with Web Storage is that although the specification used to say that any object type can be stored, in fact all browsers currently coerce to strings. That means if you want to store a JavaScript object (or an array perhaps), you’ll need to use JSON to encode and decode:

var doctors = [
   'rem',
   'rich_clark',
   'brucel',
   'jackosborne',
   'leads',
   'akamike',
   'boblet'];
localStorage.doctors = JSON.stringify(doctors);

// later that evening…
var html5docs = JSON.parse(localStorage.doctors);
alert('There be ' + html5docs.length + ' doctors in the house');

Private Browsing

Many browsers now have private (or ‘incognito’) browsing modes, where no history or other details are stored between sessions. In this situation, what happens with sessionStorage and localStorage varies widely by browser.

Safari returns null for any item set using localStorage.setItem either before or during the private browsing session. In essence, neither sessionStorage nor localStorage are available in private browsing mode.

Chrome and Opera return items set previous to private ("incognito") browsing commencing, but once private browsing commences, treat localStorage like sessionStorage (only items set on the localStorage by that session will be returned) but like localStorage for other private windows and tabs.

Firefox, like Chrome will not retrieve items set on localStorage prior to a private session starting, but in private browsing treats localStorage like sessionStorage for non-private windows and tabs, but like localStorage for other private windows and tabs.

Getters and Setters

In addition to using getItem and setItem we can use a key directly to get and set an item in sessionStorage and localStorage, like so (where the key is "keyName"):

var itemValue = window.localStorage.keyName;

localStorage and sessionStorage Limits

The webStorage specification recommends browsers implement a 5MB limit on the amount of data localStorage or sessionStorage can save for a given domain. If you try to exceed the limit that various browsers have in place (for some browsers users can change this allowance) setItem throws an error. There's no way of asking localStorage for the amount of space remaining, so it's best to set item values with a try and catch for any error:

try {
window.localStorage.setItem(key, value);
}
catch (exception) {
//test if this is a QUOTA_EXCEEDED_ERR

}
If the available space for this localStorage is exceeded, the exception object will have the name "QUOTA_EXCEEDED_ERR" and a code of 22.

As mentioned, in JavaScript strings are UTF-16 encoded, which means they are 2 bytes. So, when saving the string “John”, we are actually using 8 bytes, not 4. Which means instead of 5MB of storage space per storage area, we effectively have 2.5MB.

If the storage needs of your application are likely to exceed 5MB, then web databases are likely to be a better solution. However, the situation with web databases is complicated, with two different standards, one, webSQL widely supported but deprecated, and the other IndexedDB, currently supported only in Firefox, Chrome and IE10.

Storage Events

We can add an event listener to the window for storage events so that when a storage object has been changed then we can be notified and respond to those changes.