Description
The Web Storage API allows the browser to store application information locally (on the client) which makes it easy to persist data across web requests.
Values can be stored by using either sessionStorage or localStorage.
- sessionStorage - Values persist only as long as the window or tab in which they were stored
- localStorage - Values persist beyond window and browser lifetimes
Note: The storage database is accessed directly from the window object.
HTML5 and HTML4.01 Differences
This API is new for HTML5.
Setting Values
Setting a value in the Web Storage API can take either of the following forms:
window.sessionStorage.setItem('myKey', 'myValue');
or
window.sessionStorage.myKey = 'myValue';
Parameters
Parameter | Description |
---|---|
myKey | (required) Specifies a string which functions as the 'index' in which to store the value (this same key is used to store the item) |
myValue | (required) Specifies a string value to store |
Note: Although the HTML5 Web Storage specification allows passing non-string values, many browsers do not support this or are limited on the types they support.
Retrieving Values
Retrieving a value from the Web Storage API can take either of the following forms:
var myValue = window.sessionStorage.getItem('myKey');
or
var myValue = window.sessionStorage.myKey;
Additional Attributes and Functions
The Web Storage API defines additional attributes and functions:
length
The length attribute returns the number of key-value pairs are currently stored in the storage object.
key(index)
The key function allows retrieval of a key at a given index. The list of keys is zero-based, meaning the first key is located at key(0) and the last is key(length - 1).
removeItem(key)
The removeItem function removes the value for the given key (if found), otherwise, it does nothing.
clear()
The clear function removes all items from the storage object.
Web Storage Updates
The Web Storage API includes events to allow notifications of data updates to be communicated to subscribed listeners.
function showEvent(e) {
// key = e.key
// newValue = e.newValue
// oldValue = e.oldValue
}
//add storage event listener
window.addEventListener("storage", showEvent, true);
Examples
The following example shows how to check for support of this API:
//localStorage
if (window.localStorage) {
//localStorage supported
}
else {
//localStorage NOT supported
}
//sessionStorage
if (window.sessionStorage) {
//sessionStorage supported
}
else {
//sessionStorage NOT supported
}
This example shows how to iterate through all keys in sessionStorage:
//loop through all keys
for (var i = 0; i < window.sessionStorage.length; i++) {
var curItem = window.sessionStorage.key(i);
//do something with the value
}
Browser Support
Chrome | Firefox | IE | Safari | Opera |
---|---|---|---|---|
Miscellaneous Information
Defined In: | HTML5 |
---|