Check if IndexedDB database exists

In the onupgradeneeded callback you can check the version. (e.target.result.oldversion). If it is 0, the db didn't exist.

Edit: After some investigation. You can't be 100% sure if a new db is created. One thing I am sure of is the fact that you can only work with an indexeddb if it has a version 1 or higher. I believe that a db can exist and have a version 0 (The only fact is you can't work with it and the onupgradeneeded event will be called).

I have build my own indexeddbviewer. In that I open the indexeddb without version and if I come in to the onupgradeneeded event, that means the db doesn't exist. In that case I call the abort so it doesn't upgrade to a version 1. This is the way I check it.

var dbExists = true;
var request = window.indexeddb.open("db");
request.onupgradeneeded = function (e){
    e.target.transaction.abort();
    dbExists = false;
}

but as mentioned. It is possible that the db will continue to exist in that case, but the onupgradeneeded will always be called


With ES6 you can find an IndexedDB database by its name using the following code:

const dbName = 'TestDatabase';
const isExisting = (await window.indexedDB.databases()).map(db => db.name).includes(dbName);


I spent more than an hour playing with it and basically the only deterministic and reliable way to do that is using webkit's webkitGetDatabaseNames.

There is literally like 10 ways to test if DB exists using onupgradeneeded, but that just doesn't work in production. It got either blocked for several seconds, sometimes completely on deleting database. Those tips to abort transaction are nonsense because window.indexeddb.open("db") request does not contain transaction object... req.transaction == null

I can't believe this is real...


The following code works. I have tested it with Chrome, IE and Opera. Tested with both locally open databases and closed and with databases of different versions, so it should be accurate. The creation/deletion of the database is needed. However, it will be an atomic operation with no risk for race conditions because the spec promises to not launch to open requests in parallell if the open request results in a database creation.

function databaseExists(dbname, callback) {
    var req = indexedDB.open(dbname);
    var existed = true;
    req.onsuccess = function () {
        req.result.close();
        if (!existed)
            indexedDB.deleteDatabase(dbname);
        callback(existed);
    }
    req.onupgradeneeded = function () {
        existed = false;
    }
}

To use the function, do:

databaseExists(dbName, function (yesno) {
    alert (dbName + " exists? " + yesno);
});

Tags:

Indexeddb