Html5Storage
Background
Although HTTP is a stateless protocol, we really need to keep track of our user in between page requests. Previously cookies stored state, but cookies can only store about 4K of data and are sent to the server with each request which slows response time.
A few facts about localStorage
- Persists data between sessions on the client side
- The stored data can only be read by originating domain
- All data is stored in strings, for numbers you have to use parseInt() or parseFloat() to retrieve the values.
- The maximum safe amount per domain is about 2.5 megabytes
LocalStorage Detection and Polyfills
Click here to see if your browser supports localStorage.
The function to test is
if (Modernizr.localstorage) { alert('window.localStorage is available!'); } else { alert('window.localStorage is Not available!'); }
(If the browser doesn't support localeStorage, for polyfills you can use Remy's storage polyfill or sessionstorage.)
Syntax
LocalStorage is an associative array with a "value" being accessed via a "key", both of which are strings.
Examples:
localStorage.setItem("car","Toyota"); //sets the value, overwrites any previous value var car = localStorage.getItem("car"); //requesting a non-existant "key" will return null localStorage.removeItem("car"); //removing a non-existant key does nothing localStorage.clear(); //removes all items
Example:
The following form uses this javascript to store values in local storage
function saveInfo() { localStorage.setItem("name",$("#name").val()); localStorage.setItem("movie",$("#movie").val()); alert('Saving name \"'+localStorage.getItem("name")+"\" and movie \""+localStorage.getItem("movie")+"\""); }
Looping over stored values
You can get the number of items in localStorage with "length".
var numberOfItems = localStorage.length;
Then call "key(int)" with an index to retrieve all the values
var numberOfItems = localStorage.length; var myString = ""; for(i=0;i<numberOfItems;i++) { myKey = localStorage.key(i); myString += "\r\nitem "+i+" is "+myKey+", value is "+localStorage.getItem(myKey); } alert(myString);
How to add a handler to the storage process
You may want to trigger an event each time local storage is accessed.
if (window.addEventListener) { window.addEventListener("storage", storageHandler, false); } else { //IE 8 and less window.attachEvent("onstorage", storageHandler); };
IE will pass the event in a window event variable, not as an argument to the function
function storageHandler(e) { if (!e) { e = window.event; } }
The event has the following properties: "key","oldValue","newValue", and "url" (or "uri").
IndexedDB and WebSQL
WebSQL was the initial spec to have a SQLite database built into browsers. It is implemented in webkits browsers, Chrome and Opera, but unfortunately work on the spec has been abandoned. A new spec, IndexedDB, is being implemented by most vendors, with IE10 support in the future. As of late 2012 only Firefox and Chome support IndexedDB. Check caniuse.com for details on progress.
Backwards compatibility
Example of storing the state of a list object
Given an Html Select list like this:
Database Server: <select id="Name" name="Name"> <option>Mars</option> <option>Jupiter</option> <option>Venus</option> </select>
We can use this javascript to store the user's last selection:
<script> $(function() { $('#Name').change(function() { localStorage.setItem('dbName',$(this).attr('value')); }); if(localStorage.getItem('dbName')) { $('#Name').val(localStorage.getItem('dbName')); } }); </script>