Get in touch
Thank you
We will get back to you as soon as possible

22.7.2014

3 min read

Indexed DB Part II. Preparation.

In this article we are going to examine examples of IndexedDB practical usage. To be sure that user’s browser supports IndexedDB we need to perform some kind of check. In particular, we can call the following code:

document.addEventListener("DOMContentLoaded", function(){
    if("indexedDB" in window) {
        console.log(“Your browser support IndexedDB.");
    } else {
        console.log("Your browser doesn't support IndexedDB.");
    }
},false);
}

While IndexedDB is currently in Candidate Recommendation stage some browsers can use vendor prefixes. Browser vendors may have another implementation differing from standard IndexedDB API until the moment when unified standard is applied. Nevertheless, till then you can use following check for testing in various browsers with different prefixes:

window.indexedDB =  window.indexedDB || 
                    window.mozIndexedDB || 
                    window.webkitIndexedDB || 
                    window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || 
                        window.webkitIDBTransaction || 
                        window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || 
                     window.webkitIDBKeyRange || 
                     window.msIDBKeyRange;
if (!window.indexedDB) {
    window.alert("Your browser doesn't support IndexedDB.");
}

This implementation is not recommended for Production. To start working with any DB we should previously open it. All processes start with such request:

// Database opening
var request = window.indexedDB.open("MyDB", 2);

This request doesn’t open connection to database instantly due to the fact that work with database is asynchronous. In previously mentioned case we will have instance of  IDBOpenDBRequest that has three eventhandlers:

  1. onerror
  2. onsuccess
  3. onupgrageneeded

Onerror is called when error occurred and as argument the object of error is passed. Onsuccess is fired when database was opened successfully and the instance of opened database is returned as a result. Onupgrageneeded is called when the instance of database hasn’t yet been created or its version has been changed. This request handler should contain any manipulation with db’s inner structure – create/edit/delete ObjectStores, create indexes and so on. There is a function that opens (or creates) the database with name “MyDB” and version “3”, creates Object store with name “name”  and key-value “myKey”, and in case of success the callback is called. In its parameters the instance of opened DB is passed.

function connectToDB(callback){
var request = window.indexedDB.open("MyDB", 3);
request.onerror = function(err) {
console.log(err);
};
request.onsuccess = function() {
if(typeof callback !== 'undefined') {
callback(request.result);
}
};
request.onupgradeneeded = function() {
var db = request.result;
if(!db.objectStoreNames.contains("name")) {
var objectStore = db.createObjectStore("name", { keyPath: "myKey" });
}
};
}

You can see below the result of this method’s execution. As you have may noticed the result’s type is IDBDatabase. Among its properties you can see the database name and its version. Google chrome contains excellent tools for management of storages including IndexedDB. They are to be found in Developer Tools (F12) in tab Resources. There you can see all the available information concerning database, its version, name, accessible collections and data inside. As soon as Object Stores are ready, you can start working with them. In the IndexedDB one has possibility to store data as it is. There are also transactions in IndexedDB, that guarantee atomicity of operations in it since all reading and writing operations are combined into transaction. Due to this fact either all operations will be executed successfully or nor of them will and the database will not appear in undefined partly updated state. This method is called by transaction. As argument you should give the ObjectStore and access mode (there are two modes available: readonly and readwrite). For example:

var transaction = db.transaction(["name"], "readwrite");

Try not to use readwrite mode when you do not actually need it. Request above will return object of type IDBTransaction that has few event handlers. From this object you can also achieve access to existing object stores.

var nameStore = transaction.objectStore("name");
  1. http://habrahabr.ru/post/213515/
  2. http://code.tutsplus.com/tutorials/working-with-indexeddb--net-34673
  3. https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
  4. http://www.w3.org/TR/IndexedDB/
  5. http://habrahabr.ru/post/117473/
Thank you
We will get back to you as soon as possible

Looking for a tech partner to help you scale your project?

Let’s schedule a quick call to explore how we can support your business objectives.

Christina Berko

Let’s schedule a quick call to explore how we can support your business objectives.

Christina Berko

Client Manager

0 Comments
name *
email *

Featured Case Studies