HTML and CSS Reference
In-Depth Information
Using the key method
The API also provides the key method, which takes an index
parameter and returns the associated key. This method is useful
to enumerate the data stored in the storage object. For exam-
ple, if you wanted to show all the keys and associated data, you
wouldn't particularly know what the keys were for each of the
data items, so loop through the length of the storage object and
use the key method to find out:
for (var i = 0; i < sessionStorage.length; i++) {
alert( sessionStorage.key(i) + '=' +
¬ sessionStorage.getItem( sessionStorage.key(i) ) );
}
Another word of warning: It's conceivable that you might be
storing some value under the name of “key,” so you might write
some code like the following:
sessionStorage.setItem('key',
¬ '27152949302e3bd0d681a6f0548912b9');
Now there's a value stored against the name “key,” and we
already had a method called key on the storage object. Alarm
bells are ringing, right?
Some browsers, WebKit specifically, overwrite the key method
with your new value. The knock-on effect is the developer tools
in WebKit make use of the key method to enumerate and display
all the data associated with the storage object—so the “Storage”
view for that storage type ( sessionStorage , in our example) will
now be broken until that value has been removed.
Other browsers such as Firefox will keep the key method and
your key value stored separately. Using the expando syntax will
give you the method, and using getItem('key') will give you
the value.
NoTE I expect that as the
browsers continue to
develop, this kind of bug will be
crushed—but in the meantime,
do your very best to avoid using
names that already exist on the
storage API.
Removing data
There are three ways to remove data from the storage object
programmatically: directly using the deleter, removeItem, and
clear . The removeItem method takes a key, the same key used in
setItem and getItem , and deletes the entry for that particular item.
 
Search WWH ::




Custom Search