HTML and CSS Reference
In-Depth Information
The HTML5 Web Storage API
Web Storage is an API for persistent data storage of key-value pair data (similar to cookies) in browsers
( sessionStorage ) and window-local storage saved between sessions ( localStorage ). The Web Storage API became a
W3C Recommendation in 2013 [14].
Table 6-1 summarizes the methods of localStorage and sessionStorage .
Table 6-1. Web Storage Methods
Method with Parameters
Description
setItem(string name, string value)
Adds or updates a value in the store
getItem(string name)
Retrieves a named value from the stored name-value pairs
removeItem(string name)
Removes a named value from the stored name-value pairs
length
Number of values stored
key(long index)
Name of the key at the index
clear()
Clears the store
As an example, create two input fields for the local storage of name-value pairs, as well as a push button to let
the user set the items entered (Listing 6-15). Display the name-value pairs in a table. Create a text field where the user
can add the item to remove from the stored pairs after clicking the associated button. Add a push button that can be
used to clear the stored items. Provide another text field where the item name can be typed to retrieve its value. Since
the table is created by the displayItems function, that function should be loaded by the onload attribute on the body
element as <body onload="displayItems()"> .
Listing 6-15. A localStorage Example
<form name="lsform">
<fieldset title="WebStorage">
<legend>Local storage of name-value pairs</legend>
<p>
<label>Value:</label>
<input name="data">
</p>
<p>
<label>Name:</label>
<input name="name">
</p>
<p>
<input type="button" value="Set item" onclick="setTheItem()">
</p>
<table id="pairs"></table>
<p>
Enter name to remove item:
<input name="remove">
<input type="button" value="Remove item" onclick="removeTheItem()">
<input type="button" value="Clear items" onclick="clearItems()">
</p>
 
 
Search WWH ::




Custom Search