Simulating HTML5 Local Storage Support
I have been wanting to use HTML5’s local storage for a while, but I haven’t had a project where I can just ignore the older browsers. So I put together a little ( <1Kb gzipped ) script that checks for HTML5’s local storage API, and simulates the method for browsers that do not support it. For those browsers, the script implements a nearly identical interface to localStorage for persistent storage of name/value pairs, except it uses cookies. For the impatient types, you can see the repo at github or download the script. Below is a description of usage:
localStorage.setItem( key , value ); // saves a new name/value pair if the key doesn't exist, otherwise // updates the value localStorage.getItem( key ); // returns the value associated with the given key, if it exists // returns null if the key doesn't exist localStorage.length; // the number of unique keys stored localStorage.removeItem( key ); // deletes the name/value pair with the given key, if it exists // if it does not exist, exits localStorage.clear(); // delete all name/value pairs currently stored localStorage.key( n ); // returns the name of the nth key in the list, will return null if n is // greater than or equal to localStorage.length
If the localStorage object is available, the setup script exits and allows the method to work normally. Otherwise, it will use the same interface to create a string of name/value pairs to store in cookies. You can use all the methods described above, but it does not support direct access to data, such as ‘localStorage.name = “bob” ;’. One issue is that the older browsers with slow performance will experience another setback when storing large amounts of data, because the cookies will be included in headers.
There are two types of storage methods in the new Web Storage Specification: localStorage and sessionStorage. The sessionStorage data will only persist for the life of the browser window, whereas localStorage will last indefinitely, depending on the browser. This script uses the localStorage, but can be switched to sessionStorage pretty easily. There are a few resources out there already where you can learn a little bit more. Currently, the specification is supported by IE8, Firefox3.5, Safari4, and Chrome (localStorage only).
Download or Check out the repo on github.
[Note: I've done some brief testing on most browsers, but if you run into a problem, let me know]



