Lesson 1: Introducing web storage CHAPTER 15 561
■■key(index) Method that finds a key at a given index. The World Wide Web
Consortium (W3C) indicates that if an attempt is made to access a key by using an
index that is out of the range of the collection, null should be returned. However, some
browsers will throw an exception if an out-of-range index is used, so it’s recommended
to check the length before indexing keys.
var key = localStorage.key(1);
Very high browser support
Another benefit of localStorage, as seen in the previous section, is that localStorage, in addi-
tion to sessionStorage, is well supported in modern browsers. In fact, it’s the only one of the
four storage options that is consistently supported across desktop and mobile browsers.
Determining whether the user’s browser supports web storage
Although most browsers support web storage, it’s still a good idea to verify that it’s available
in case the user is running an older browser version. If it’s not available, you could experi-
ence a null reference exception the first time an attempt is made to access localStorage or
sessionStorage. There are several ways to check availability; the following is one example.
function isWebStorageSupported() {
return 'localStorage' in window;
}
if (isWebStorageSupported()) {
localStorage.setItem('firstName', $('#firstName').val());
}
The popular JavaScript library, Modernizr, comes with a method that could do this check
for you.
if (Modernizr.localstorage) {
localStorage.setItem('firstName', $('#firstName').val());
}
Amount of data that can be kept in web storage
The localStorage object provides much more space than was available with older tools.
Modern browsers support a minimum of 5 MB of data, which is substantially more than is
allowed through cookies (which are limited to 4 KB each).
NOTE STORAGE CAPACITY
The 5 MB limit is currently recommended by the W3C, but it’s ultimately up to the browser
vendors to determine how much they will allow. Currently, Internet Explorer supports a
10 MB limit.