Jump to content

How to use HTML5's Web Storage

0
  chco's Photo
Posted Aug 21 2010 11:00 AM

The following excerpt is from HTML5: Up and Running. Below the author expounds on the new feature of HTML5 Web Storage, allowing local storage of data.
Introducing HTML5 Storage

What I refer to as “HTML5 Storage” is actually a specification named Web Storage. This was at one time part of the HTML5 specification proper, but was split out into its own specification for uninteresting political reasons. Certain browser vendors also refer to it as “Local Storage” or “DOM Storage.” The naming situation is made even more complicated by some related, similarly named, emerging standards that I’ll discuss later in this chapter.

So what is HTML5 Storage? Simply put, it’s a way for web pages to store named key/value pairs locally, within the client web browser. Like the data stored in cookies, this data persists even after you navigate away from the website, close your browser tab, exit your browser, or what have you. But unlike with cookies, this data is never transmitted to the remote web server (unless you go out of your way to send it manually). And unlike all previous attempts at providing persistent local storage (described in the preceding section), it is implemented natively in web browsers, so it is available even when third-party browser plug-ins are not.

Which browsers? As Table 7-1 shows, HTML5 is supported by the latest versions of pretty much all browsers...even Internet Explorer!

Table 7-1. HTML5 Storage support
IEFirefoxSafariChromeOperaiPhoneAndroid
8.0+3.5+4.0+4.0+10.5+2.0+2.0+


From your Javascript code, you’ll access HTML5 Storage through the localStorage
object on the global window object. Before you can use it, you should detect whether
the browser supports it:

function supports_html5_storage() {
  return ('localStorage' in window) && window['localStorage'] !== null;
}


Or, instead of writing this function yourself, you can use Modernizr to detect support for HTML5 Storage:

if (Modernizr. localstorage) {
  // window. localStorage is available!
} else {
  // no native support for HTML5 Storage :(
  // maybe try dojox.storage or a third-party solution
}


Cover of HTML5: Up and Running
Learn more about this topic from HTML5: Up and Running. 

If you don't know about the new features available in HTML5, now's the time to find out. This book provides practical information about how and why the latest version of this markup language will significantly change the way you develop for the Web. HTML5: Up & Running carefully guides you though the important changes in this version with lots of hands-on examples, including markup, graphics, and screenshots. You'll learn how to use HTML5 markup to add video, offline capabilities, and more -- and you’ll be able to put that functionality to work right away.

Learn More Read Now on Safari


Tags:
0 Subscribe


0 Replies