562 CHAPTER 15 Local data with web storage
Reaching the storage limit
If the storage limit is reached, or if the user manually turns off storage capabilities, a
QuotaExceededError exception is thrown. The following is an example of how you can use a
try/catch block to keep your application from failing if that happens.
try{
localStorage.setItem('firstName', $('#firstName').val());
}
catch(e) {
// degrade gracefully
}
Storing complex objects
Currently, only string values can be stored in web storage, but sometimes you might need to
store more interesting items such as arrays or JavaScript objects. To accomplish this, you can
take advantage of some of the available JavaScript Object Notation (JSON) utility methods.
The following example creates a JSON object and uses the stringify() method to convert
the value to a string that can then be placed in web storage.
var person = { firstName: 'Glenn', lastName: 'Johnson' };
localStorage.setItem('glenn', JSON.stringify(person));
You can then use the parse() method to deserialize a new instance of the object from the
string representation that was stored in the previous example.
var person = JSON.parse(localStorage.getItem('glenn'));
Don’t forget that a potential drawback to cookies is that they are always included in web
requests and responses, even if you don’t use them. The situation when using web storage is
the opposite; its values are never automatically passed to the server. You can do this yourself
by including values in an AJAX call or by using JavaScript to copy the values into posted form
elements.
Using short-term persistence with sessionStorage
In the previous section, you learned how to use localStorage, which, like cookies, is designed
to retain data across multiple sessions. However, if you want to purge stored information, you
must use the removeItem() or clear() method.
In addition to localStorage, you can use sessionStorage; it is also a Storage object, so the
same methods and properties exist. The difference is that sessionStorage retains data for a
single session only. After the user closes the browser window, records stored are automatically
cleared. This is an important advantage because only a limited amount of space is available.
At their core, both localStorage and sessionStorage are firmly dedicated to their respec-
tive browsing contexts. Because that context for localStorage includes other tabs and win-
dows within the same URL base, its data is shared among all open instances. In contrast,