HTML5 Local Storage – 5 Useful Tips

Page content

HTML5 Local Storage is a browser based key-value database that is available for client side applications. Java programmers (like me) will find that  HTML5 Local Storage is very similar to HashMap (or Hashtable). It is important to remember that Local Storage is available to client side applications even across browser restarts. In that context, Local Storage is similar to cookies. **But unlike cookies, Local Storage is not accessible to the server side applications. **Also cookies provide very limited storage (4 KB).

Here is an example of the two most important methods of localStorage object.

localStorage.setItem("foo", "bar");
localStorage.getItem("foo");

JavaScript language allows several other ways to access localStorage.

var storeValue = localStorage["foo"];

For more introductory material check this out.

Tip - 1 - Pay attention to the URL

Browsers persist HTML5 Local Storage on a per domain basis. So a web application can only access Local Storage defined for its domain. Not just the domain but subdomain and HTTP vs HTTPS are also used to identify the domain. For example, a key-value stored in Local Storage for http://www.mysite.com is not available https://www.mysite.com. So if you want to share client side data between applications on different domain or sub-domains, you need to use re-directs.

On the other hand if you host multiple web applications on the same domain (hosted as sub-directories) then all your web applications share the information stored in Local Storage. While this could be useful sometimes, care must be taken to avoid one application from over-writing the values of another application. It is good to identify the key along with application name or other identifiers.

Tip - 2 - Size does matter

The HTML5 specification has arbitrarily fixed the maximum storage size per domain to 5 MB. This includes keys as well as values. While  5 MB worth of client side data is quite a bit, ensure that you handle the exception QUOTA_EXCEEDED_ERR and probably cleanup the storage.

Tip - 3 - Store and retrieve data types

Local Storage supports only string values to be persisted. When you call setItem method, it internally converts the value object to String and persists it. So additional steps need to be taken to store and retrieve objects of different data types. Fortunately we can use JSON parsing for this purpose.

The technique is to use JSON.stringify() and JSON.parse() functions to perform this conversion automatically. JavaScript allows us to add newer methods to existing objects. So it is advisable to incorporate this technique into the _standard localStorage object _itself. This can done as follows:

Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

With the above code you can invoke

localStorage.getObject("foo");
localStorage.setObject("foo", obj);

The above code is courtesy - http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage

Tip - 4 - Store multiple values for a single key

If you want to store multiple values for a single key, then this tip is very useful. I borrowed this technique from http://paperkilledrock.com/2010/05/html5-localstorage-part-two/. Here is what you need to do:

  • Create an array and push different values into it.
var values = new Array();
values.push(value1);
values.push(value2);
values.push(value3);
  • Stringify the array using the join method by specifying a separator. Note choose a separator that is unlikely to appear in your values.
  • Persist this string into Local Storage.
try {
	localStorage.setItem(key, values.join(";")); //store the item in the database
} catch (e) {
	if (e == QUOTA_EXCEEDED_ERR) {
		alert("Quota exceeded!");
	}
}
  • While retrieving fetch the concatenated String from Local Storage and use String.split() to parse the different values.
var valueFromStore = localStorage.getItem(key); // get the String from Local Storage
var values = valueFromStore.split(";"); // get an Array back

Tip - 5 - Always check for Browser Support

A very large number of modern browsers support Local Storage but as a web application developer you may still encounter browsers that do not support many HTML5 constructs and certainly not Local Storage. So you are well advised to check whether your browser supports Local Storage or not. While there are many ways to check, I strongly recommend Modernizr API (why re-invent the wheel).

if (Modernizr.localstorage) {
  // localStorage is supported
} else {
  // localStorage not supported
}