Skip to Main Content
HTML5: Up and Running
book

HTML5: Up and Running

by Mark Pilgrim
August 2010
Intermediate to advanced content levelIntermediate to advanced
222 pages
7h 12m
English
O'Reilly Media, Inc.
Content preview from HTML5: Up and Running

Using HTML5 Storage

HTML5 Storage is based on named key/value pairs. You store data based on a named key, and then you can retrieve that data with the same key:

interface Storage {
  getter any getItem(in DOMString key);
  setter creator void setItem(in DOMString key, in any data);
};

The named key is a string. The data can be any type supported by JavaScript, including strings, Booleans, integers, or floats. However, the data is actually stored as a string. If you are storing and retrieving anything other than strings, you will need to use functions like parseInt() or parseFloat() to coerce your retrieved data into the expected JavaScript datatype.

Calling setItem() with a named key that already exists will silently overwrite the previous value. Calling getItem() with a nonexistent key will return null rather than throwing an exception.

Like other JavaScript objects, you can treat the localStorage object as an associative array. Instead of using the getItem() and setItem() methods, you can simply use square brackets. For example, this snippet of code:

var foo = localStorage.getItem("bar");
// ...
localStorage.setItem("bar", foo);

could be rewritten to use square-bracket syntax instead:

var foo = localStorage["bar"];
// ...
localStorage["bar"] = foo;

There are also methods for removing the value for a given named key and clearing the entire storage area (that is, deleting all the keys and values at once):

interface Storage {
  deleter void removeItem(in DOMString key);
  void clear();
};

Calling ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

HTML5 in Action

HTML5 in Action

Greg Wanish, Rob Crowther, Joe Lennon, Charles Brindle
HTML5 Cookbook

HTML5 Cookbook

Christopher Schmitt, Kyle Simpson
AngularJS

AngularJS

Shyam Seshadri, Brad Green

Publisher Resources

ISBN: 9781449392154Errata Page