Cookies are a form of local storage for the web, unfortunately they aren't that useful
- Are included with every HTTP request
- Slow down your web application
- Potentially send unecrypted data unless using SSL
- Are limited to 4KB of data, enough to slow, not enough to be useful
Ideal Storage would look like...
- lots of space
- on the client
- exists after page refreshes
- no server transmission
None of the Ideal Storage solutions existed prior to HTML5, instead it was a number of different browser based or 3rd party plugins that had different requirements and generated different user experiences.
HTML5 Storage:
- aka WebStorage, Local Storage, DOM Storage
- allows local storage of key/value pairs even after navigating away from the page/exiting the browser and is never transmitted
- accessed through JavaScript via
localStorageobject on the global window object - offers 5 MB of data storage
- throws
QUOTA_EXCEEDED_ERRif data storage is exceeded
Check whether a browser supports it by writing a function to see if localStorage returns null. Or use Modernizr to detect it:
if (Modernizr.localstorage) {
// window.localStorage is available!
} else {
// no native support for HTML5 storage :(
// maybe try dojox.storage or a third-party solution
}
Data is stored in Key Value pairs
-
stored on key
-
retreived with same key
-
supports all JavaScript data types
- when stored all data types are stored as a string
- need to used functions to convert back to expected type when retrieving
-
setItem()if key already exisits it will be overwritten -
getItem()if retrieving key that doesn't exsist will get null -
methods for call set and get Item:
var foo = localStorage.getItem("bar"); OR var foo = localStorage["bar"]; localStorage.setItem("bar", foo); OR localStorage["bar"] = foo; -
removeItem()remove a key -
get total number of values in storage:
interface Storage { readonly attribute unsigned long length; getter DOMString key(in unsigned long index); };
Storage Area Changes:
- To track changes trap the
storageevent - the
storageevent is created whensetItem(),removeItem(), orclear()are called and actually modify the local storage- if the local storage isn't modified the storage event won't be created
- trapping storage event:
if (window.addEventListener) {
window.addEventListener("storage", handle_storage, false);
} else {
window.attachEvent("onstorage", handle_storage);
};
- handling storage event:
function handle_storage(e) {
if (!e) { e = window.event; }
}
- e will be a StorageEvent object with the following properties:
- key - type = string, name of key modified
- oldValue - type any, previous value
- newValue - type any, new value
- url - type string, page that called the method that triggered the modfication