Web Storage
Web Storage provides several APIs for saving data on the client in a fashion similar to browser cookies. There is a Storage object for data that needs to persist between restarts named localStorage and one for data that will be purged once the session ends named sessionStorage. The data is stored as key/value pairs. These two objects implement the functions listed in Table 1-1.
Table 1-1. Web Storage Functions
Function Name |
Description |
setItem(key:String, value) |
Creates a key/value pair given the specified values. Some implementations require the value to be a string. |
getItem(key:String) |
Returns the item specified by the given key. |
removeItem(key:String) |
Removes the item identified by the given key. |
clear() |
Clears all key/value pairs from the Storage object. |
key(index:long) |
Returns the key for the specific index. |
Each Storage object also has a length property indicating the number of present key/value pairs.
Web Storage offers a more fluent API we can use in lieu of the getItem and setItem functions listed in Table 1-1. The alternate API uses an array-like means of referencing a key. To set a localStorage key/value pair with the values of a hometown newspaper, we could use the following, for example:
localStorage['newspaper'] = 'The Baltimore Sun';
Likewise, we could retrieve that value with just the left half of the preceding expression:
localStorage['newspaper'];
In the context of game programming, we could use Web Storage to store user high scores as well as data for saved games.