HTML and CSS Reference
In-Depth Information
HTML5 introduces two new APIs that you can use to store data on a client: LocalStorage and SessionStorage. In the
next few sections, you learn how to use LocalStorage and SessionStorage to store data on a client.
Note that when I refer to client-side storage in this chapter, I am referring to LocalStorage and SessionStorage, not
IndexedDB, which is also classed as a client-side storage API but is a little too advanced for this topic.
LocalStorage is a simple way of storing data using key/value pairs. The LocalStorage API consists of an object that
provides several functions to store, access, and delete data from the client. You access the API using JavaScript.
All the data that your web application stores is placed in a datastore that is accessible only through your application.
This means that the data your application saves cannot be accessed by other applications, and vice versa. Applica-
tions are identified by their domain names. If you have sub-domains, such as and , they are treated as separate applications and are each given their own datastore.
Using Key/Value Pairs
The concept of key/value pairs is explained in Chapter 5, which examines how form data is passed via parameters
in a URL.
If you want to store a simple piece of data, such as a user's name, you create a key that describes the data (in this
case, name ) and then use the data (that is, a specific user's name) as that key's value. This mechanism is good for
storing simple unstructured data; however; if you want to store data about multiple users at once, you might be bet-
ter off utilizing a system that supports structured data, such as a database.
The technical term for assigning datastores to specific domains is sandboxing .
To start using LocalStorage, you first need to get familiar with the localStorage object and its associated func-
tions. Fire up your developer tools console; you're going to need it in this section. After you work through the ex-
amples in the next few pages, you use what you learn here to add LocalStorage capabilities to the bookings form on
the Joe's Pizza Co. website.
setItem(key, value)
The setItem() function has two parameters. The first parameter, key , is used to assign the name by which you
access the data. The second, value , is where you put the data you want to save.
Search WWH ::

Custom Search