56

How can one remove a whole IndexedDB database from JavaScript, as opposed to just an object store? I'm using the IndexedDB shim, which may use WebSQL as its backend.

I'd mainly like to know how to do this for the PhantomJS (headless) browser, although Chrome, Safari (on iPad) and IE10 are other important browsers.

aknuds1
  • 65,625
  • 67
  • 195
  • 317
  • Just being curious. Why do you want to remove it? – hequ Apr 07 '13 at 11:17
  • 1
    @hequ Automated testing purposes. – aknuds1 Apr 07 '13 at 11:18
  • possible duplicate of [How to delete indexedDB in Chrome](http://stackoverflow.com/questions/9384128/how-to-delete-indexeddb-in-chrome) – Josh Jul 29 '14 at 02:28
  • @Josh But that question is about how to delete the database manually, whereas this is about deleting it programatically?? Also, it's about Chrome specifically.. – aknuds1 Jul 29 '14 at 05:32
  • I understood the questions to be the same. The answer is essentially the same. But ok, vote retracted. – Josh Jul 29 '14 at 17:35
  • @Josh The accepted answer (to the other question) is also manual anyway. – aknuds1 Jul 29 '14 at 18:02

2 Answers2

97

As far as I can tell, one should use indexedDB.deleteDatabase:

var req = indexedDB.deleteDatabase(databaseName);
req.onsuccess = function () {
    console.log("Deleted database successfully");
};
req.onerror = function () {
    console.log("Couldn't delete database");
};
req.onblocked = function () {
    console.log("Couldn't delete database due to the operation being blocked");
};

I can confirm that it works with PhantomJS 1.9.0 and Chrome 26.0.1410.43.

aknuds1
  • 65,625
  • 67
  • 195
  • 317
  • 3
    Yep that's what you want, I use it extensively in the automated tests for db.js - https://github.com/aaronpowell/db.js/blob/master/tests/specs/indexes.js#L15 – Aaron Powell Apr 08 '13 at 00:01
  • 1
    Is there a way to do this for all databases on an origin without knowing their names? – jacobq Nov 13 '18 at 14:49
  • 1
    you must call db.close() before delete, if you already open. otherwise you will get onblocked event https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/close – mili May 15 '19 at 06:05
  • 1
    @iX3 you can call `indexedDB.databases()` for a list of all databases, read more at https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/databases – Tom Saleeba Jul 29 '19 at 05:30
  • @TomSaleeba thanks for the tip -- looks like a draft specification, but I'll watch for future updates there. – jacobq Jul 29 '19 at 10:53
2

I found that the following code works OK but to see the DB removed in the Chrome Resources Tab I have had to refresh the page. Also I found I had problems with the Chrome debug tools running while doing transactions. Makes it harder to debug but if you close it while running code the code seems to work OK. Significant also is to set a reference to the object store when opening the page. Obviously the delete part of the code is in the deleteTheDB method.

Code derived from example provided by Craig Shoemaker on Pluralsight.

var IndDb = {
    name: 'SiteVisitInsp',
    version: 1000,
    instance: {},
    storenames: {
        inspRecords: 'inspRecords',
        images: 'images'
    },
    defaultErrorHandler: function (e) {
        WriteOutText("Error found : " + e);
    },
    setDefaultErrorHandler: function (request) {
        if ('onerror' in request) {
            request.onerror = db.defaultErrorHandler;
        }
        if ('onblocked' in request) {
            request.onblocked = db.defaultErrorHandler;
        }
    }

};

var dt = new Date();
var oneInspRecord =
        {            
            recordId: 0,
            dateCreated: dt,
            dateOfInsp: dt,
            weatherId: 0,
            timeArrived: '',
            timeDeparted: '',
            projectId: 0,
            contractorName: '',
            DIWConsultant: '',
            SiteForeman: '',
            NoOfStaffOnSite: 0,
            FileME: '',
            ObservationNotes: '',
            DiscussionNotes: '',
            MachineryEquipment: '',
            Materials: ''
        };

var oneImage =
{
    recordId: '',
    imgSequence: 0,
    imageStr: '',
    dateCreated: dt
}


var SVInsp = {
    nameOfDBStore: function () { alert("Indexed DB Store name : " + IndDb.name); },
    createDB: function () {
        openRequest = window.indexedDB.open(IndDb.name, IndDb.version);

        openRequest.onupgradeneeded = function (e) {
            var newVersion = e.target.result;
            if (!newVersion.objectStoreNames.contains(IndDb.storenames.inspRecords)) {
                newVersion.createObjectStore(IndDb.storenames.inspRecords,
                    {
                        autoIncrement: true

                    });
            }

            if (!newVersion.objectStoreNames.contains(IndDb.storenames.images)) {
                newVersion.createObjectStore(IndDb.storenames.images,
                    {
                        autoIncrement: true
                    });
            }
        };

        openRequest.onerror = openRequest.onblocked = 'Error'; //resultText;

        openRequest.onsuccess = function (e) {
            //WriteOutText("Database open");
            IndDb.instance = e.target.result;
        };

    },

    deleteTheDB: function () {
        if (typeof IndDb.instance !== 'undefined') {
            //WriteOutText("Closing the DB");

            IndDb.instance.close();
            var deleteRequest = indexedDB.deleteDatabase(IndDb.name)

            deleteRequest.onblocked = function () {
                console.log("Delete blocked.");
            }

            deleteRequest.onerror =
                function () {
                    console.log("Error deleting the DB");
                    //alert("Error deleting the DB");
                };
                //"Error deleting the DB";

            deleteRequest.onsuccess = function () {

                console.log("Deleted OK.");
                alert("*** NOTE : Requires page refresh to see the DB removed from the Resources IndexedDB tab in Chrome.");
                //WriteOutText("Database deleted.");

            };


        };

    }
}
CYoung
  • 307
  • 1
  • 10