25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Using the <strong>HTML</strong>5 Web Storage API<br />

CHAPTER 9 ■ USING THE <strong>HTML</strong>5 WEB STORAGE API<br />

The Web Storage API is surprisingly simple to use. We’ll start by covering simple storage and retrieval of<br />

values and then move on to the differences between sessionStorage and localStorage. Finally, we’ll<br />

look at the more advanced aspects of the API, such as event notification when values change.<br />

Checking for Browser Support<br />

The storage database for a given domain is accessed directly from the window object. Therefore,<br />

determining if a user’s browser supports the Web Storage API is as easy as checking for the existence of<br />

window.sessionStorage or window.localStorage. Listing 9-1 shows a routine that checks for storage<br />

support and displays a message about the browser’s support for the Web Storage API. This routine is<br />

part of the browser-test.html file and located in the code/storage folder. Instead of this code, you can<br />

also use Modernizr, which handles some cases that may result in a false positive, such as the lack of<br />

storage support in Chrome's incognito mode.<br />

Listing 9-1. Checking for Web Storage Support<br />

function checkStorageSupport() {<br />

//sessionStorage<br />

if (window.sessionStorage) {<br />

alert('This browser supports sessionStorage');<br />

} else {<br />

alert('This browser does NOT support sessionStorage');<br />

}<br />

//localStorage<br />

if (window.localStorage) {<br />

alert('This browser supports localStorage');<br />

} else {<br />

alert('This browser does NOT support localStorage');<br />

}<br />

}<br />

Figure 9-1 shows this check for storage support in action.<br />

215

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!