black data storage racks

Storing Your Data in HTML5

Get a feel for working with HTML5's flexible web storage

In the world of application development, data rules. Every application, whether on the desktop or web, requires the storage of some sort of data, and developers have been saving their "stuff" in different places for many years. There have been many techniques to store information on the web. From cookies to sessions to forms, working in a stateless world has always been a challenge. In this month's article, we are going to continue on the developer side and look at one of the more useful and widely needed aspects of HTML5: web storage.

In the Beginning

You will hear web storage called different things: DOM storage, local storage, HTML5 storage. But its true name, as defined by the HTML5 Web Storage specification, is web storage.

The cool thing about web storage is that it is supported by all the major browsers, including mobile browsers:

On the desktop:

  • Microsoft Internet Explorer (IE) 8 and later
  • Mozilla Firefox 3.5 and later
  • Apple Safari 4 and later
  • Google Chrome 4 and later
  • Opera 10.5 and later

On mobile devices:

  • Windows Phone 7 and later
  • Apple iPhone 2 and later
  • Android 2 and later

This widespread support is quite an accomplishment; few of the HTML5 specifications can claim the same level of support. We find it interesting how nonchalantly disk space (web storage) is described in the specification:

A mostly arbitrary limit of five megabytes per origin is recommended. Implementation feedback is welcome and will be used to update this suggestion in the future.

This size is supported in most browsers (i.e., Firefox, Chrome, and Opera), although IE supports 10MB (or as the documentation puts it—queue the Dr. Evil voice—10 million bytes). In addition, Opera allows the user to decide how much storage each site can use, although this figure is not known to the developer at design time. Because you will need to make sure that your web application works across all browsers, I suggest keeping the 5MB in mind while developing. If you exceed this limit, you will receive a QUOTA_EXCEEDED_ERR and will need to process that error appropriately. At this point, if you are used to other mediums, such as Adobe Flash or Silverlight, you might be wondering whether you can prompt the user to request additional space. Unfortunately, the answer is no.

Since we do not live in a perfect world, you will have users running browsers that do not fit into the previous list. Therefore, you will need to check whether the browser supports web storage. You can use the following code to do so:

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

You can use this code as shown in Figure 1; this code allows you to perform a simple check whenever you attempt to save something to storage.

if (!supportsStorage()) {
	alert('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
	try {
		//save something
	} catch (e) {
	 	 if (e == QUOTA_EXCEEDED_ERR) {
	 	 	 alert('Quota exceeded!'); 
//save some other way??
		}
	}
}

As you can see, we are also catching the specific quota exceeded error so that we can handle it and alert the user. You can then decide the best option for your application: using a different storage option or showing the user the error. Understand that this quota is a per-domain quota (a domain being a combination of schema, host, and port). So you will have separate quotas for http:// and https://. But this also means that if another application on the host http://www.YourAppSite.com uses up the quota, then you are out of luck. This issue is described in the HTML5 Web Storage specification section 7.2. I particularly like the reference to geocities.com:

Different authors sharing one host name, for example users hosting content on geocities.com, all share one local storage object. There is no feature to restrict the access by pathname. Authors on shared hosts are therefore recommended to avoid using these features, as it would be trivial for other authors to read the data and overwrite it.

So be certain that you know who is writing applications for the domain that you are using, or you expose your saved data to others. In addition, do not save sensitive data in web storage. Anyone sharing your domain would find it all too easy to loop through and read your data.

Before we dive too deeply into the saving of data, you need to know that there are actually two types of defined storage: session storage and local storage.

Session Storage

Session storage is designed for scenarios in which the user is carrying out a single transaction. The HTML5 sessionStorage attribute is available only to the window or tab in which it was initiated and only while that window stays active. When the window or tab is closed (i.e., the session has ended), the data ceases to exist. This approach has an advantage over cookies, not only because you have more room to store data (5MB versus 4KB for a cookie), but because this attribute is scoped only for the window that is open. Cookies can leak to another window if you open another browser instance while your session is still active.

Local Storage

Local storage is designed for scenarios in which you want the data to persist beyond a single session. This storage spans all windows that you might have open on that domain. If you set or modify data in one window, that data will be available to all other windows that are opened to that domain. In addition, the data stays available after you close your browser, unless explicitly deleted by the developer or user. This approach allows you to store data over instances, across windows, and on the client side, without using cookies.

Using HTML5 Storage

Now that we have examined the different kinds of storage, let's take a look at how to use them. The HTML5 Web Storage specification defines the following:

  • Length <attribute>
  • Key() <function>
  • getItem<function>
  • setItem()<function>
  • removeItem()<function>
  • clear()

These attributes and functions are available for both sessionStorage and localStorage. In essence, we are saving key/value pairs of data. Because both types of storage use the same methods, we will show examples using only session storage.

Setting and Retrieving Data

Using the Web Storage API, you can set and retrieve data in several ways. We can use the setItem and getItem methods to place and retrieve data:

sessionStorage.setItem('firstName', "Daniel");
sessionStorege.setItem('lastName', "Egan");

var fName = sessionStorage.getItem('firstName');
var lName = sessionStorage.getItem('lastName);

If you want to save your fingers from doing some typing, then you can also use Expandos to add and retrieve data:

sessionStorage.firstName = "Daniel";
sessionStorage.LastName – "Egan";

var fName = sessionStorage.firstName;
var lName = sessionStorage.lastName;

Understanding that all data is saved as a DOMString is vital for several reasons. First, because the API stores numbers as strings, a developer needs to be sure to convert numbers when retrieving data, as the example in Figure 2 shows.

sessionStorage.setItem('price', 32);
sessionStorage setItem('tax', 11);

// will return 3211
var totalPrice = sessionStorage.getItem('price ') + sessionStorage.getItem('tax '); 

//instead you will need to parse the data
var intPrice = parseInt(sessionStorage.getItem('price');
var intTax = parseInt(sessionStorage.getItem('tax');
var totalPrice = intPrice + intTax;

Remember that the "+" symbol serves a dual purpose: It performs both arithmetic and concatenation. Second, as a developer you won't be limiting yourself to simple key/value pairs, so you will need a way to store more complex structures as strings.

Saving More Complex Structures

Although saving key/value pairs locally in a 5MB storage area is convenient, most developers will want to save more complex objects. As noted previously, all data is stored as a string, so the process of saving an object into storage saves the object name "[Person person]", not the actual data. To get around this limitation, we can use JavaScript Object Notation (JSON), an open-source and text-based way of storing data. Take a look at this simple example of JSON as a person object:

var person = { "firstName" : "John",
  		"lastName"  : "Doe",
  		"age"       : 23 };

If we want to store this object in session storage, we can encode and decode it, using the JSON.stringify and JSON.parse methods. First, we save the object to storage:

sessionStorage.setItem('person', JSON.Stringify(person));

Later, when we want to retrieve the data, we use JSON.Parse:

var person = JSON.Parse(sessionStorage.getItem('person');

Clearing Data

Now that we have filled our storage with data, we need a way to remove it. There are two ways to remove data that you have placed in storage: removeItem and clear. The removeItem method is very similar to getItem, in that if you pass it a key, it will remove the value associated with that key:

sessionStorage.removeItem('firstName');

If you want to remove everything that you have stored in storage, you can use the clear method:

sessionStorage.clear();

Keep in mind that the examples we have been using are for session storage and will go away when the browsing session is completed. The same is not true for local storage. Because we have a limit of 5MB per domain, make sure that you keep your storage area clear.

In this article, we have focused specifically on web storage as a way to store data locally. As we mentioned previously, web storage has been widely implemented across all major browsers. This type of storage is a step up from cookies and is a much simpler and cleaner way to save your data, whether you need to save information for one session or across sessions.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish