HTML and CSS Reference
In-Depth Information
An overview of the API
Since both sessionStorage and localStorage descend from
the Web Storage API, they have the exact same API (from the
specification):
readonly attribute unsigned long length;
getter DOMString key(in unsigned long index);
getter DOMString getItem(in DOMString key);
setter creator void setItem(in DOMString key, in any data);
deleter void removeItem(in DOMString key);
void clear();
This API makes setting and getting data very easy. The setItem
method simply takes a key and a value. The getItem method
takes the key of the data you want and returns the content,
as shown here:
sessionStorage. setItem ('twitter', '@rem');
alert( sessionStorage. getItem ('twitter') ); // shows @rem
It's worth making very clear that the getItem method only sup-
ports strings. This is important because it means if you try to
store an object, it actually returns “[Object object].” More impor-
tantly, this means numbers being stored are actually being
returned as strings, which can cause errors in development.
To h i g h l i g h t t h e p To s s i b l e p r To b l e m s , h e r e 's a n e x a m p l e : L e t 's s a y
that Bruce runs a website selling videos of himself parading
as a professor of science. You've added a few of these videos
to your shopping basket because you're keen to learn more
about “synergies.” The total cost of your shopping basket is $12,
and this cost is stored in sessionStorage . When you come to
the checkout page, Bruce has to add $5 in shipping costs. At
an earlier point during your application, $12 was stored in
sessionStorage . This is what your (contrived) code would look like:
sessionStorage.setItem('cost', 12);
// once shipping is added, Bruce's site tells you the
¬ total cost:
function costWithShipping(shipping) {
alert(sessionStorage.getItem('cost') + shipping);
}
// then it shows you the cost of the basket plus shipping:
costWithShipping(5);
 
Search WWH ::




Custom Search