HTML and CSS Reference
In-Depth Information
10.1 Local Storage
You want to store some data (like user preferences or partially entered form data) per-
sistently on a user's system, so that it's available on a subsequent visit.
HTML5 introduced two new APIs for in-browser persistent data storage: sessionStor
age , which stores data only for the lifetime of the browser instance/session, and local
Storage , which stores data persistently “forever” (which in this case means, “until either
the code or the user clears it out”).
Both interfaces have the same API. The difference between the two is basically how
long the browser persists the data.
Data stored in these containers must be strings. If you need to store
complex data objects, one good option is to serialize the object into
JSON, using JSON.stringify() .
To test if a browser supports either of the storage APIs, use the following feature-detect:
var storage_support = window. sessionStorage || window. localStorage ;
To store some data for only the current browser instance (i.e., so it goes away when
the user closes the browser), use sessionStorage :
var user_id = "A1B2C3D4";
var user_data = {
name: "Tom Hanks",
occupation: "Actor",
favorite_color: "Blue"
// ...
sessionStorage.setItem (user_id, JSON.stringify (user_data));
To store some data for a longer period of time, use localStorage :
var user_id = "A1B2C3D4";
var user_prefs = {
keep_me_logged_in: true,
start_page: "daily news"
// ...
localStorage.setItem (user_id, JSON.stringify (user_prefs));
These code snippets look almost identical because the APIs are identical.
Search WWH ::

Custom Search