Opening a database in HTML5

This database is local to the browser and only available to the user. IndexedDB databases follow the same rules as cookies and local storage. A database is unique to the domain it was loaded from. So for example, a database called “Foo” created at foo.com will not conflict with a database of the same name at goo.com. Not only will it not conflict, it won’t be available to other domains as well. You can store data for your web site knowing that another web site will not be able to access it.

Opening a database is done via the open command. In basic usage you provide a name and a version. The version is very important for reasons I’ll cover more later. Here’s a simple example: var openRequest = indexedDB.open(“test”,1);
Opening a database is an asynchronous operation. In order to handle the result of this operation you’ll need to add some event listeners. There’s four different types of events that can be fired:
1-success
2-error
3-upgradeneeded
4-blocked

You can probably guess as to what success and error imply. The upgradeneeded event is used both when the user first opens the database as well as when you change the version. Blocked isn’t something that will happen usually, but can fire if a previous connection was never closed.
Typically what should happen is that on the first hit to your site the upgradeneeded event will fire. After that – just the success handler. Let’s look at a simple example (test3.html).

var idbSupported = false;
var db;

document.addEventListener(“DOMContentLoaded”, function(){

if(“indexedDB” in window) {
idbSupported = true;
}

if(idbSupported) {
var openRequest = indexedDB.open(“test”,1);

openRequest.onupgradeneeded = function(e) {
console.log(“Upgrading…”);
}

openRequest.onsuccess = function(e) {
console.log(“Success!”);
db = e.target.result;
}

openRequest.onerror = function(e) {
console.log(“Error”);
console.dir(e);
}

}

},false);
Once again we check to see if IndexedDB is actually supported, and if it is, we open a database. We’ve covered three events here – the upgrade needed event, the success event, and the error event. For now focus on the success event. The event is passed a handler via target.result. We’ve copied that to a global variable called db. This is something we’ll use later to actually add data. If you run this in your browser (in one that supports IndexedDB of course!), you should see the upgrade and success message in your console the first time you run the script. The second, and so forth, times you run the script you should only see the success message.


Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top