Cover by Mark Pilgrim

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required