HTML5 LocalStorage

published on March 3, 2012 in technical

LocalStorage has crossed my mind many times when planning a few applications. OOP implementation in Javascript is also something I like and keep testing, so let me share a little OOP Javascript LocalStorage usage example.

1. Example

First, let us create an HTML5 document:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>

Now, let us add the Javascript code to the page:

<script>
"use strict"

if (!window.Modules) {
	window.Modules = {};
}

if (!window.Modules.Storage) {

	window.Modules.Storage = function() {
		if (typeof(localStorage) == 'undefined' ) {
			console.log('No HTML5 localStorage support.');
		}
	}
}

window.Modules.Storage.prototype = {
	set: function(key, value) {
		try {
			return localStorage.setItem(key, value);
		} catch (e) {
			if (e == QUOTA_EXCEEDED_ERR) {
				alert('Quota exceeded!');
			}
		}
	},

	get: function(key) {
		return localStorage.getItem(key);
	},

	remove: function(key) {
		return localStorage.removeItem(key);
	}

}

window.onload = function() {
	window.storage = new Modules.Storage;
	var key = 'test';
	storage.set(key, 'Just a simple string');
	document.write('Storage content: ' + localStorage.length);
	document.write('
Storage content: ' + storage.get(key));
	storage.remove(key);
	document.write('
Storage content: ' + localStorage.length);
};
</script>

All this little code does, is put something in the storage, remove it from there and write element counts to the document.

2. Possible Usages

We have lots of possible usages, from storing content offline, to caching Javascript or CSS, or just replacing cookies.

3. Try It

I put together an example here, check it out if you wish. It works great in the latest stable browsers.

It also workes on mobile Safari (Yay!)