564 CHAPTER 15 Local data with web storage
No transaction support
Another benefit of other storage options that is missing from web storage is support for
transactions. Although difficulties are unlikely in the majority of applications, applications
using web storage can run into problems if a user is modifying the same value in localStorage
within multiple open browser tabs. The result would be a race condition in which the second
tab immediately overwrites the value inserted by the first tab.
Quick check
■■You would like to store the user’s name after he authenticates on your site, but
he will need to authenticate again on his next visit, at which time you would
reload his information (including name). Which storage mechanism should
you use?
Quick check answer
■■sessionStorage. Although you could use localStorage to store the user’s name, it
would be held permanently. Placing it in sessionStorage would purge it auto-
matically after the window is closed.
Lesson summary
■■Web storage provides you with an easy method for storing key/value pairs of data
without relying on a server.
■■With nearly universal support across current desktop and mobile browsers, web stor-
age is the most supported form of offline data storage.
■■Web storage comes in two forms, which have the same methods.
■■localStorage Shares data across all windows and tabs within the same origin.
■■sessionStorage Data is sandboxed to only the current tab or window and is
cleared when closed.
■■Reads/writes to web storage can be performed only synchronously.
■■Web storage does not support advanced features such as transactions or indexing.
■■Only storage for string values is currently supported within web storage, but storage
for more complex objects can be achieved by using the JSON.stringify() and JSON.
parse() utility methods.
Lesson review
Answer the following questions to test your knowledge of the information in this lesson. You
can find the answers to these questions and explanations of why each answer choice is correct
or incorrect in the “Answers” section at the end of this chapter.