HTML and CSS Reference
In-Depth Information
To pull data (if available) from the storage container, use code like this:
var user_id = "A1B2C3D4";
var user_data = { /* defaults */ };
var user_prefs = { /* defaults */ };
if (sessionStorage. getItem (user_id)) {
user_data = JSON.parse ( sessionStorage.getItem (user_id));
}
if (localStorage. getItem (user_id)) {
user_prefs = JSON.parse ( localStorage.getItem (user_id));
}
These storage APIs allow you to very simply set and retrieve key/value data, where the
value is a string but can represent anything you want, including the string serialization
of a complex data object.
The localStorage and sessionStorage APIs are synchronous in design,
which makes them easier to use but can result in slower performance.
Be careful using these APIs in performance-sensitive code.
Discussion
The solution for storing data client-side that most likely first popped into your head is
cookies. However, cookies have a number of problems that make them less than ideal
for storing user data. In this chapter we explore a new alternative: the HTML5 storage
(also known as “DOM storage”) APIs.
sessionStorage and localStorage share the same API; the difference, as belied by their
names, is in how long they persist the data. For data that you only need to persist for
the lifetime of a browser session—things such as user login data, shopping cart con-
tents, etc.—the sessionStorage API is probably your best option. For more long-lived
data—things such as application preferences— localStorage may be a better option.
Many browsers even persist sessionStorage data across browser crash-
es. This makes it a great container to temporarily mirror data being
entered into form fields: if the browser crashes, you can restore what
the user was typing.
The APIs for sessionStorage and localStorage are as follows:
getItem( key )
Returns an item of data from the storage container, referenced by its key
setItem( key , item )
Adds an item of data to the storage container, referenced by its key
 
Search WWH ::




Custom Search