HTML and CSS Reference
In-Depth Information
key( index )
Returns the key for an item of data at the numerical index specified
removeItem( key )
Removes an item from the storage container, referenced by its key
clear()
Clears out all data in the current storage container
length
Identifies how many items of data are in the storage container
Most browsers give up to 5 MB of space for these storage containers. For most practical
applications, this is more than enough. Be prepared to detect and handle errors, though,
if you are writing more data than the browser allows.
Unlike cookies (which have explicit expirations) and sessionStorage (which has im-
plicit expiration at the end of the browser instance/session), the localStorage API has
no expiration at all. This has both good and bad consequences.
The benefit is that data stays around as long as you need it to unless the user explicitly
clears it herself, but the downside is that the 5 MB limit may be reached more quickly
than anticipated, especially if old data is abandoned and left forever to sit idle in the
storage container.
One common solution is to implement a custom expiration mechanism, by storing a
timestamp with each piece of data and then checking manually on each page load to
see if any old data needs to be removed.
For instance, your ecommerce site might keep a record of all items the user has viewed
across various visits, so it can display that in a “Previously Viewed” area. However, you
don't want the application to remember those items forever, so you might manually
expire entries that are older than, say, 21 days:
// first, store the currently viewed item in the history
var current_item = {
id: "ABCD0123",
data: "Mens' Running Shoes",
ts: new Date() // current timestamp, used for expiration check later
};
localStorage.setItem(current_item.id, JSON.stringify(current_item));
// then manually "expire" all old entries
var key, data;
for (var i=0; i<localStorage. length ; i++) {
key = localStorage. key (i);
data = localStorage.getItem(key);
if ( data.ts < ((new Date()) - 60*60*24*21)) { // more than 21 days old
localStorage. removeItem (key);
}
}
 
Search WWH ::




Custom Search