HTML5, JavaScript, webdev

How To Use IndexedDB – Code And Example

IndexedDB is an evolving web standard for the storage of significant amounts of structured data in the browser and for high performance searches on this data using indexes. IndexedDB leaves room for a third-party JavaScript library to straddle the underlying primitives with a BTree API, and I look forward to seeing initiatives like BrowserCouch built on top of IndexedDB. Intrepid web developers can even build a SQL API on top of IndexedDB.

I’ve work today to create this example in order to push it to MDC IndexDB page later… I found few things that didn’t work on Firefox 4 (but since we have Firefox 5 from last night) – I’ve just put them in the comments. Also, Chrome 12 (and above) works great.
You might want to check that the pages you developing on are served from a server and not a local file, because on firefox it won’t work…

You can go here and see a working example or browse the code below and get a beer.

Here is a code that will show you all the basic features:
To check the code with highlights you might want to check The code of this example on github

Here are some main snippets of code:

// Our local DB
var idb_; 
// Our DB request obj
var idbRequest_;    
//
// just a simple way to show what we are doing on the page
var idbLog_ = document.getElementById('idb-log');
var idResultsWrapper_ = document.getElementById('idb-results-wrapper');

// IndexedDB spec is still evolving - see: http://www.w3.org/TR/IndexedDB/
// various browsers keep it
// behind various flags and implementation varies.
if ('webkitIndexedDB' in window) {
    window.indexedDB = window.webkitIndexedDB;
    window.IDBTransaction = window.webkitIDBTransaction;
} else if ('mozIndexedDB' in window) {
    window.indexedDB = window.mozIndexedDB;
}

// Open our IndexedDB if the browser supports it.
if (window.indexedDB) {
    idbRequest_ = window.indexedDB.open("Test", "Our Amazing test object IndexDB");
    idbRequest_.onerror = idbError_;
    idbRequest_.addEventListener('success', function(e) {
        // FF4 requires e.result. IDBRequest.request isn't set
        // FF5/Chrome works fine.
        idb_ = idbRequest_.result || e.result;
        idbShow_(e);
    }, false);
}

// on errors - show us what is going wrong
function idbError_(e) {
    idbLog_.innerHTML += '

Error: ' + e.message + ' (' + e.code + ')

';
}

// In cases we add/remove objects - show the user what is changing in the DB
function idbShow_(e) {
    if (!idb_.objectStoreNames.contains('myObjectStore')) {
        idbLog_.innerHTML = "

Object store not yet created.

";
        return;
    }

    var msgBoard = [];
    // Ready is default - make sure NOT to pass empty array in the first param as it use to be something like: []
    var transaction = idb_.transaction(idb_.objectStoreNames, IDBTransaction.READ_ONLY);
    // Get all results.
    var request = transaction.objectStore("myObjectStore").openCursor();
    //
    //
    // This callback will continue to be called until we have no more results.
    request.onsuccess = function(e) {
        // FF4 requires e.result. IDBRequest.request isn't set
        // FF5/Chrome works fine.
        var cursor = request.result || e.result;
        if (!cursor) {
  idResultsWrapper_.innerHTML = '

    ' + msgBoard.join('') + '

';
  return;
        }
        msgBoard.push('

  • ', cursor.key, ' ',
            '=> ', cursor.value, '  ',
            '[Delete]
  • ');
            cursor.continue();
        }
        request.onerror = idbError_;
    }

    // Simple example to show all our records in the DB
    function showAll_() {
        document.getElementById("ourList").innerHTML = "" ;
        var request = window.indexedDB.open("Test",
        "Our Test database");
        request.onsuccess = function(event) {
            // Enumerate the entire object store.
            // request = event.currentTarget.result.objectStoreNames("myObjectStore").openCursor();
            var transaction = idb_.transaction(idb_.objectStoreNames, IDBTransaction.READ_ONLY); // Ready is default.
            var request = transaction.objectStore("myObjectStore").openCursor();
            request.onsuccess = function(event) {
      var cursor = request.result || event.result;
      // If cursor is null then we've completed the enumeration.
      if (!cursor) {
          return;
      }
      var element = document.createElement("div");
      element.textContent = "key: " + cursor.key + "=> Value: " + cursor.value;
      document.getElementById("ourList").appendChild(element);
      cursor.
          continue ();
            };
        };
    }

    —-
    Main Source: The IndexDB Spec on w3.org

    Standard

    4 thoughts on “How To Use IndexedDB – Code And Example

    1. greenido says:

      It’s wordpress.com that won’t let me do some nice highlighting… Anyway, you have the link to github – so you can browse the code for real.

    Comments are closed.