IE userData Persistence
IE5 and later enable client-side storage by attaching a proprietary “DHTML behavior” to a document element. You can do that with code like this:
var
memory
=
document
.
createElement
(
"div"
);
// Create an element
memory
.
id
=
"_memory"
;
// Give it a name
memory
.
style
.
display
=
"none"
;
// Never display it
memory
.
style
.
behavior
=
"url('#default#userData')"
;
// Attach a magic behavior
document
.
body
.
appendChild
(
memory
);
// Add it to the document
Once you add the “userData” behavior to an element, that element
gets new load()
and save()
methods. Call load()
to load stored data. You must pass a
string to this method—it is like a file name, identifying a particular
batch of stored data. When data is loaded, the name/value pairs become
available as attributes of the element, and you can query them with
getAttribute()
. To save new data,
set attributes with set
Attribute()
and then call
the save()
method. To delete a
value, use removeAttribute()
and
save()
. Here is an example, using
the memory
element initialized
above:
memory
.
load
(
"myStoredData"
);
// Load a named batch of saved data
var
name
=
memory
.
getAttribute
(
"username"
);
// Get one piece of stored data
if
(
!
name
)
{
// If it wasn't defined
name
=
prompt
(
"What is your name?); // Get user input
memory.setAttribute("
username
", name); // Set it as an attribute
memory.save("
myStoredData
"
);
// And save it for next time
}
By default, data saved with userData has an indefinite lifetime and lasts until you delete it. But you ...
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.