This function checks if the database exists. Use the onupgradeneeded event, if the version is 1 and the event is triggered, it means that the database does not exist, but is created with the window.indexedDB.open(name) function, which means that you should remove it.
When the onsuccess event fires, but not the onupgradeneeded event (Variable dbExists remains true) indicates that the database existed before and returns true.
/**
* Check if a database exists
* @param {string} name Database name
* @param {function} callback Function to return the response
* @returns {bool} True if the database exists
*/
function databaseExists(name, callback) {
var dbExists = true;
var request = window.indexedDB.open(name);
request.onupgradeneeded = function (e) {
if (request.result.version === 1) {
dbExists = false;
window.indexedDB.deleteDatabase(name);
if (callback) callback(dbExists);
}
};
request.onsuccess = function (e) {
if (dbExists) {
if (callback) callback(dbExists);
}
};
}
The output of the function is through a callback function. The form of use is as follows:
var name = "TestDatabase";
databaseExists(name, function (exists) {
if (exists) {
console.debug("database " + name + " exists");
} else {
console.debug("database " + name + " does not exists");
}
});
[sorry for my english]