HTML5 : Learn how to use IndexedDB

IndexedDB is an API for storing data in user’s browser.11 HTML5 : Learn how to use IndexedDB One can also use cookies and local storage but they don’t provide database like usability the way IndexedDB do. The data stored in IndexedDB is persistence.  It provides rich query abilities and is available both in online and offline mode. It can be used to store large amount of data.

Note: IndexedDB is currently a Candidate Recommendation and is only available in modern desktop web browsers.

IndexedDB stores data in form of objects along with an index key. Everything that happens in IndexedDB happens through transactions. The objects are grouped into object stores. The IndexedDB contains object stores and these object stores contain objects along with a unique keyPath.

IndexedDB vs LocalStorage

Although both were developed to provide client side data storage but both have different approaches and should be chosen according to the needs. localStorage stores data in key-value pair but unlike IndexedDB, they are not stored in form of objects. Instead, it stores only string key-value pairs. A simple trick to store objects in localstorage is to use JSON.stringify(), similarly to store it back to object form after reading you will need to do JSON.parse(). But it will not be a good solution when storing large number of complex objects. Moreover, localstorage was designed for smaller data and provides synchronous API.

IndexedDB is great for handling large amount of data and comes with asynchronous API. It uses indexes to store data and transactions to perform operations. It even supports simple data types. IndexedDB may seem better than localstorage,but its API is complex to use and currently only latest desktop browsers are supported.

For basic storage you may continue to use local storage but if you are going to store large amount of data, IndexedDB will be a better suited option as it will also allow you to perform complex search queries.

IndexedDB vs Web SQL

WebSQL was also a web storage API to store data at client side. Unlike IndexedDB which is a NoSQL database, WebSQL used SQL queries to store data. W3C no longer maintains this specification. According to http://www.w3.org/TR/webdatabase/

Beware. This specification is no longer in active maintenance and the Web Applications Working Group does not intend to maintain it further.

Since, its no longer maintained, you should not use it in your project.

IndexedDB vs Cookies

Cookies may sound tasty but they are not. Cookies are sent and received with every http request resulting in additional traffic. For e.g. if you have 10KB of cookies and made 10 request, then total 100KB of data will be transferred. Also, cookies are only strings and hence need to be parsed. Also, the space of storing cookies is limited and many users block their cookies. Hence cookies can be only good for storing very small non-crucial data.

How to use IndexedDB

To understand IndexedDB, I have created a basic web app that stores the roll numbers and names of students in IndexedDB. It provides basic add, remove, access and update option.

https://github.com/SuyashMShepHertz/indexedDB_sample

Opening a Database

Firstly you need to make sure, that your browser supports IndexedDB. As mentioned earlier, it is still a candidate recommendation and hence not supported in all browsers.

1
2
3
4
5
6
                window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
 
                if(!window.indexedDB)
                {
                    console.log("Your Browser does not support IndexedDB");
                }

Once, we know IndexedDB is supported, we have to open a database. You can not simply open a database, rather IndexedDB requires you to create a request to open a database.

1
               var request = window.indexedDB.open("testDB", 2);

here first parameter is the name of database and second parameter is version of database. The version allows you to represent your DB’s current schema i.e the object stores stored in it and their structures. If you upgrade your database you will only need to create/delete few object stores rather than creating/deleting all the object stores.

When you will increase the version of your database, onupgradeneeded event will be triggered. Along with onupgradeneeded, there are success, error and blocked events.

1
2
3
4
5
6
7
8
9
10
11
12
13
                   var db;
                    request.onerror = function(event){
                        console.log("Error opening DB", event);
                    }
                    request.onupgradeneeded   = function(event){
                        console.log("Upgrading");
                        db = event.target.result;
                        var objectStore = db.createObjectStore("students", { keyPath : "rollNo" });
                    };
                    request.onsuccess  = function(event){
                        console.log("Success opening DB");
                        db = event.target.result;
                    }

onupgradeneeded event will be called whenever the webpage is hit for the first time on user’s web browser or if there is an upgrade in version of database. Hence, you will have to create your object stores only in onupgradeneeded event. If there is no upgrade in version and the page has been opened previously, you will get onsuccess event. onerror event occurs if there is some error. onblocked event occurs if previous connection was never closed.

In above code snippet, we are creating a Object Store named “students” with index key “roll no”.

Adding Object to ObjectStore

To add data in our DB, we first need to create a transaction with read write permission on our object store. To perform any action on object store we need to create a transaction. Following it, access our object store and add the data to it.

1
2
3
4
5
6
7
8
9
10
11
                    var transaction = db.transaction(["students"],"readwrite");
                    transaction.oncomplete = function(event) {
                        console.log("Success");
                    };
 
                    transaction.onerror = function(event) {
                        console.log("Error");
                    };  
                    var objectStore = transaction.objectStore("students");
 
                    objectStore.add({rollNo: rollNo, name: name});

Removing Object from ObjectStore

Deletion is similar to addition, you need to create transaction and call delete function with the key of the object to be removed.

1
                    db.transaction(["students"],"readwrite").objectStore("students").delete(rollNo);

I have mixed up statements to make it more easier but they perform the same.

Accessing an object with the key

Use the get() function passing the key of the object to be retrieved.

1
2
3
4
                    var request = db.transaction(["students"],"readwrite").objectStore("students").get(rollNo);
                    request.onsuccess = function(event){
                        console.log("Name : "+request.result.name);    
                    };

Updating an Object

To update an object, first get that object and then after making changes put back it to object store.

1
2
3
4
5
6
7
8
                    var transaction = db.transaction(["students"],"readwrite");
                    var objectStore = transaction.objectStore("students");
                    var request = objectStore.get(rollNo);
                    request.onsuccess = function(event){
                        console.log("Updating : "+request.result.name + " to " + name);
                        request.result.name = name;
                        objectStore.put(request.result);
                    };

The full source code of above sample web page is here. If you have any questions or need any further assistance, please feel free to write us at support@shephertz.com.

twitter HTML5 : Learn how to use IndexedDBfacebook HTML5 : Learn how to use IndexedDBgoogle HTML5 : Learn how to use IndexedDBlinkedin HTML5 : Learn how to use IndexedDBpinterest HTML5 : Learn how to use IndexedDBreddit HTML5 : Learn how to use IndexedDBstumbleupon HTML5 : Learn how to use IndexedDBtumblr HTML5 : Learn how to use IndexedDB

Leave a Reply

Your email address will not be published. Required fields are marked *


five + 2 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>