반응형

Having fun with HTML5 — Local Storage and Session Storage


API

The full API spec­i­fi­ca­tion for the local­Stor­age and ses­sion­Stor­age objects can be found here. At the time of writ­ing, this is how the com­mon Stor­age inter­face look:

image

Demo

I’ve put together a quick demo here to illus­trate how to detect and use the local and ses­sion stor­age to get, set, remove and clear stored items (well, basi­cally, cov­ers each of the avail­able meth­ods on the Stor­age inter­face above).

The page itself is sim­ple and crude, just a cou­ple of <div> and most impor­tantly two tables which I use to show all the key value pairs stored in the local and ses­sion storage:

image

Intro­duc­ing the new place­holder attribute

You might have noticed that the two text boxes had place­holder text sim­i­lar to that famil­iar search box in Firefox:

text boxes with place holder text Firefox search box

This is done using HTML5’s place­holder attribute for the <input> tag:

1
2
<input id="keyText" placeholder="Enter key"/>
<input id="valueText" placeholder="Enter value"/>

Nice and easy, eh? ;-)

Set­ting an item

To add a new key value pair or update the value asso­ci­ated with an exist­ing key, you just have to call the setItem method on the intended stor­age object:

1
2
3
4
5
6
7
8
9
10
11
12
13
// adds a new key to both local and session storage
function setKey() {
var key = $("#keyText").val();
var value = $("#valueText").val();
if (Modernizr.localstorage) {
localStorage.setItem(key, value);
}
if (Modernizr.sessionstorage) {
sessionStorage.setItem(key, value);
}
showKeys();
}
Remov­ing an item

Ear­lier in the showStorageKeys(type, table) func­tion, I added a row to the rel­e­vant table for each key value pair in the stor­age includ­ing a but­ton with a han­dler for the onclick event. The han­dlers are cre­ated with the cor­rect stor­age type (“local” or “ses­sion”) and key for the cur­rent row baked in already so that they will call the removeItem(type, key) func­tion with the cor­rect parameters:

1
2
3
4
5
6
7
// removes an item with the specified key from the specified type of storage
function removeItem(type, key) {
// get the specified type of storage, i.e. local or session
var storage = window[type + 'Storage'];
storage.removeItem(key);
showKeys();
}
Clear­ing all items

Finally, the ’”Clear” but­tons under­neath the tables call the clear­LocalKeys() and clearS­es­sion­Keys() func­tion to remove all the key value pairs in the cor­re­spond­ing storage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function clearLocalKeys() {
clearKeys("local");
}
function clearSessionKeys() {
clearKeys("session");
}
// clear all the held keys in the specified type of storage
function clearKeys(type) {
// get the specified type of storage, i.e. local or session
var storage = window[type + 'Storage'];
// clear the keys
storage.clear();
showKeys();
}


반응형

+ Recent posts