HTML5 Guidelines for Web Developers

(coco) #1
8.1 Storage 207

Table 8.1 Methods and attributes of the “Storage interface”


Attribute/Method Return Value Description
length integer Number of key/value pairs associated
with this object (read-only access)
key(n) DOMString Name of the key in position n
getItem(key) data Value of the given key (a DOMString)
setItem(key,data) void Saves the value data of the key
removeItem(key) void Deletes the content of the key
clear() void Deletes all key/value pairs of this
object

Similar to cookies, the Storage interface manages key/value pairs, where the key
has the type DOMString. According to the W3C DOM specification, DOMStrings
are strings encoded in UTF-16, which means you could even use special charac-
ters as key values, for example the German umlauts (ü, ö, ä). You could, but usu-
ally it is advisable not to; instead, it is better to use only characters and numbers
from the US-ASCII character set. Even an empty string is a legal key but is usually
not chosen on purpose. If an already existing key is used in the function setItem,
the existing value is replaced by the new one.


Apart from setItem() and getItem(), the Web Storage API also offers another ac-
cess method, which is often easier to read. If you, for example, want to save the
key currentTemp with the value 18 in localStorage, the following line is enough:


localStorage.currentTemp = 18;


Not surprisingly, the value can also be read back this way:


alert(localStorage.currentTemp);


If localStorage contains an unknown number of items, the “Storage interface”
method key works well:


for (var i=0;i<localStorage.length;i++) {
var item =
localStorage.getItem(localStorage.key(i));
alert("Found item "+item);
}


The specification states that values can be of any type, but the current browser
implementations save all values as strings. To save complex data types such as

Free download pdf