localStorage and sessionStorage
Browsers that implement the “Web Storage” draft specification
define two properties on the Window object: localStorage
and sessionStorage
. Both properties refer to a
Storage object—a persistent associative array that maps string keys to
string values. Storage objects work much like regular JavaScript
objects: simply set a property of the object to a string, and the
browser will store that string for you. The difference between
localStorage
and sessionStorage
has to do with
lifetime and scope: how long
the data is saved for and who the data is accessible to.
Storage lifetime and scope are explained in more detail below.
First, however, let’s look at some examples. The following code uses
localStorage
, but it would also
work with sessionStorage
:
var
name
=
localStorage
.
username
;
// Query a stored value.
name
=
localStorage
[
"username"
];
// Array notation equivalent
if
(
!
name
)
{
name
=
prompt
(
"What is your name?"
);
// Ask the user a question.
localStorage
.
username
=
name
;
// Store the user's response.
}
// Iterate through all stored name/value pairs
for
(
var
name
in
localStorage
)
{
// Iterate all stored names
var
value
=
localStorage
[
name
];
// Look up the value of each one
}
Storage objects also define methods for storing, retrieving, iterating, and deleting data. Those methods are covered in Storage API.
The Web Storage draft specification says that we should be able to store structured data (objects and arrays) as well as primitive values and built-in types ...
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.