Chapter 5. Client-Side Data Storage

Most software applications need to store data in some sort of persistent fashion in order to be useful. When it comes to web apps, this task has traditionally been handled with either a server-side database or cookies set in the browser. With the advent of HTML5, web developers now have a couple more options: Web Storage, and Web SQL Database.

Web Storage

Web Storage comes in two flavors—localStorage and sessionStorage—and are very similar to cookies in that they allow you to use JavaScript to set name/value pairs that you can retrieve across multiple page reloads.

Unlike cookies, however, Web Storage data is not sent across the wire with the browser request—it lives entirely in the client. Therefore, it’s feasible to store much more data than you can with cookies.

Note

At the time of this writing, browser size limits for Web Storage are still in flux. However, my most recent tests indicate that the limit is right around 2.5 MB.

Functionally, localStorage and sessionStorage are the same. They differ only in terms of persistence and scope:

localStorage

Data is saved even after the window is closed and is available to all windows (or tabs) that are loaded from the same origin (must be the same domain name, protocol, and port). This is useful for things like application preferences.

sessionStorage

Data is stored with the window object. Other windows/tabs are not aware of the values, and the data is discarded when the window/tab is closed. Useful ...

Get Building Android Apps with HTML, CSS, and JavaScript, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.