HTML5 Local Web Storage Database Tutorial And Example

May 13, 2011 — HTML5 provides a number strong and flexible specifications that allow web developers to create more compelling applications using client-side methods. Perhaps the most useful thus far is HTML5’s Web Storage that allows data storage on a users machine.

HTML 5 Web Storage

Up until the introduction of HTML 5 web storage, the most common method for storing data locally on a user's machine was to use cookies and sessions. While these methods are adequate for storing simple values anything other than trivial amounts becomes problematic. This is where HTML 5’s Web Storage comes in to play. Referred to as "Local Storage", "DOM Storage" or a "Web SQL Database", HTML 5 web storage allows a developer the freedom to store large amounts of data on the clients machine that persists past past sessions, doesn't require unencrypted data to be transmitted to the server and stored items are available on the entire domain.

This web storage tutorial sets out to provide a practical use for openDatabase(), localStorage.setItem(), localStorage.getItem() and localStorage.clear().

Browser Support
As you might expect with any HTML 5 specification older browsers versions and browser with Javascript turned off do not allow this method. The good news is that all modern browsers support it and will continue to do so. The following browsers support HTML 5 Web Storage:

  • Internet Explorer 8+
  • FireFox 3.5+
  • Chrome 4+
  • Safari 4+
  • Opera 10.5+
  • iOS 2+
  • Webkit 2+

HTML 5 Web Storage Example

The linked example illustrates the use of Javascript, the HTML5 specification Web Storage and HTML5's contenteditable to dynamically store and retrieve data located on a users machine. Please note the following example will open in a new window. There you will be able to play with a demo and download a full working script: Web Storage Demo

How It All Works

The first thing we need to do is check if the users browser supports Web Storage. A small function does the job by attempting to determine whether the window object of the browser supports the the HTML5 localStorage. The statement will then catch any errors. The next segment displays an alert if local storage isn't supported.

var db = null;
function html5_storage_support() {
  try {
    return 'localStorage' in window && window['localStorage'] !== null;
  } catch (e) {
    return false;
  }
}

if (!html5_storage_support) {
  alert("This Might Be a Good Time to Upgrade Your Browser or Turn On Jeavascript");
} else {

Web Storage - openDatabase()

The first thing that we will do is create and open a database by initializing openDatabase() with the following parameters:

  • "MyContacts" is the database name
  • "1" is the database version
  • "My Personal Contacts" is the Display name of the database
  • "100000" is the size of the database in bytes (100kb)
  db = openDatabase("MyContacts", "0.1", "My Personal Contacts", 100000);

Storing The Data - localStorage.setItem()

Here we create the function "storeMyContact(id)". The first three lines set the values we want to store by getting the innerHTML of the element by it's ID. What is unique to the web storage specification is localStorage.setItem(). The first object is name of the key we are storing (mcFull) and the second is the value we previously defined (fullname). Since we have three pieces of data we want to store we will repeat this process three times with different keys and associated values.

  function storeMyContact(id) {
    var fullname	= document.getElementById('fullname').innerHTML;
    var phone		= document.getElementById('phone').innerHTML;
    var email		= document.getElementById('email').innerHTML;
    localStorage.setItem('mcFull',fullname);
    localStorage.setItem('mcPhone',phone);
    localStorage.setItem('mcEmail',email);
  }

Getting The Data - localStorage.getItem()

The function function getMyContact() allows us to retrieve the data that we have stored or provides default values if the data doesn't exist. As with the previous function we combine some Javascript with localStorage.getItem().

The first task of this function is to see if there is any data stored. In this case we only need to see if "mcFull" has a value (A phone number and email address wouldn't have been saved without a name). We do this by calling localStorage.getItem(). This allows us to access the stored values and to define the Javascript variables fullname, phone and email if they exist. If they don't exist we will define them.

The last portion of this function is intended to populate the the inner HTML of an element by it's ID with the values we previously defined in the function.

  function getMyContact() {
    if (localStorage.getItem('mcFull')) {
      var fullname	= localStorage.getItem('mcFull');
      var phone		= localStorage.getItem('mcPhone');
      var email		= localStorage.getItem('mcEmail');
    }
    else {
      var fullname	= 'Enter A Name';
      var phone		= 'Enter A Phone Number';
      var email		= 'Enter An Email Address'
    }
    document.getElementById('fullname').innerHTML = fullname;
    document.getElementById('phone').innerHTML = phone;
    document.getElementById('email').innerHTML = email;
  }

Clearing The Data - localStorage.clear()

The last function we create is to give the user the ability to delete the data stored on their local machine. By using localStorage.clear() all data stored in MyContacts will be erased. If you don't want to use this nuclear option you can also specify the key which you wish to erase by using removeItem(someKey)

  function clearLocal() {
    clear: localStorage.clear(); 
    return false;
  }
}

Displaying The And Saving Data

The last bit of code we need to employ is to define the ID of the element span, div etc... in this case we are using the span tag we then call the storage function storeMyContact(this.id) on key up when ever something is typed within the inner HTML.

<span id="fullname" contenteditable="true" onkeyup="storeMyContact(this.id)"></span>
<span id="phone" contenteditable="true" onkeyup="storeMyContact(this.id)"></span>
<span id="email" contenteditable="true" onkeyup="storeMyContact(this.id)"></span>

Calling The Data

We can now use the the function getMyContact() to get the values that will be used to populate the element called just prior.

getMyContact();
You can also download a full working version of the script here or visit the web storage example here

Putting It All Together


<script>
var db = null;
function html5_storage_support() {
  try {
    return 'localStorage' in window && window['localStorage'] == null;
  } catch (e) {
    return false;
  }
}
//CHECK TO SEE IF THE BROWSER IS COMPATIBLE 
if (!html5_storage_support) {
  alert("This Might Be a Good Time to Upgrade Your Browser or Turn On Jeavascript");
} else {
  
	//OPEN AND OR CREATE THE DATABASE ON THE USERS MACHINE
	db = openDatabase("MyContacts", "1", "My Personal Contacts", 100000);
  
	function storeMyContact(id) {
		var fullname	= document.getElementById('fullname').innerHTML;
		var phone		= document.getElementById('phone').innerHTML;
		var email		= document.getElementById('email').innerHTML;
		localStorage.setItem('mcFull',fullname);
		localStorage.setItem('mcPhone',phone);
		localStorage.setItem('mcEmail',email);
	}
  //GET STORED VALUES FROM KEYS TO DEFINE JAVASCRIPT VALUES OR DEFINE IF THEY DO NOT EXIST
  function getMyContact() {
    if ( localStorage.getItem('mcFull')) {
      var fullname	= localStorage.getItem('mcFull');
      var phone		= localStorage.getItem('mcPhone');
      var email		= localStorage.getItem('mcEmail');
    }
    else {
      var fullname	= 'Click And Enter A Name';
      var phone		= 'Click And Enter A Phone Number';
      var email		= 'Click And Enter An Email Address';
    }
    document.getElementById('fullname').innerHTML = fullname;
    document.getElementById('phone').innerHTML = phone;
    document.getElementById('email').innerHTML = email;
  }

  function clearLocal() {
    clear: localStorage.clear(); 
    return false;
  }
}
</script>
<div id="myContacts">
  <div>N: <span id="fullname" contenteditable="true" onkeyup="storeMyContact(this.id)"></span></div>
  <div>P: <span id="phone" contenteditable="true" onkeyup="storeMyContact(this.id)"></span></div>
  <div>E: <span id="email" contenteditable="true" onkeyup="storeMyContact(this.id)"></span></div>
  <div><a onclick="clearLocal(); getMyContact();" href="javascript:void(0);">Clear All Of My Data</a></div>
</div>
<script>
  getMyContact();
</script>

Add a Comment

Comments

Posted Subject Comment
vishvash
December 30, 2011
Microsoft JScript runtime e... When run With Internet Explorer 8 ...
in mozila and google chrome it's fine
kiwi
November 28, 2011
Not HTML5 Nice article... but i believe it is false to state that "web storage" is part of HTML5! ... its is a stand alone API.
Poster
July 06, 2011
Not SQL this example does not use SQL or a local database as your article states. You are creating and never using the database connection. The only thing you are accomplishing in this example is saving a single entry to the local storage of the browser. There is no support for multiple entries or need for a 'key' given the above code.
Author
July 02, 2011
In reply to: jesus2099
db object
db object
The db var is not necessary. It is actually a remnant of a more sophisticated script that Local SQL Storage script we have written for a future HTML 5 tutorial
jesus2099
July 01, 2011
db object Hi there,
I don’t understand why there is a db variable created and then it is not used anywhere in the code.
Thanks for your help.
sreekanth
May 16, 2011
HTML5 Local Storage Tutorial Hi this is very nice. Thank you for your effort to explain HTML5 local storage. I think I can build off of your example