Can you ever alter the structure of an indexedDB database after it has been opened in firefox?

蹲街弑〆低调 提交于 2019-12-10 11:58:38

问题


var db;
var version = 1;
var request = indexedDB.open("myDB", version);
request.onsuccess(function(e) {db = e.target.result;});
// db.close(); //??? happens async and has no callback
var request2 = indexedDB.open("myDB", ++version);
request.onsuccess = function() { console.log("success"); };
request.onerror = function() { console.log("error"); }; // called if db existed when page was loaded
request.onblocked = function(){console.log("blocked");}; // called on init creation
request.onupgradeneeded = function(){console.log("onupgradeneeded");};

I need to be able to open the db, read an object store, and then alter the db. It looks like you can only alter the db structure once per page load.

This works just fine in Chrome when using the deprecated setVersion method.


回答1:


The IndexedDB API isn't easy to use. A few things:

1) upgradeneeded won't fire until there are no other open connections to the db. Uncomment the db.close() line. But db won't be an IDBDatabase object until request has received a success event, so you have to wait for that.

2) The request2 object has no event handlers on it. You probably meant to put request2 instead of request on those last 4 lines in the code sample.

3) The first request.onsuccess assignment is wrong.

4) The error handler will be called if the the database on disk has a version higher than the one you are passing to open.

Try this:

indexedDB = indexedDB || mozIndexedDB;
var db;
var request = indexedDB.open("myDB");
request.onsuccess = function(e) {
    db = e.target.result;
    var version = db.version;
    db.close();
    var request2 = indexedDB.open("myDB", ++version);
    request2.onsuccess = function() { console.log("success"); };
    request2.onerror = function() { console.log("error"); };
    request2.onblocked = function() { console.log("blocked"); };
    request2.onupgradeneeded = function() { console.log("onupgradeneeded"); };
};

The console will show:

onupgradeneeded
success

If not:

  1. Check that no other tabs have connections opened to this db.
  2. Add handlers for the other three events to request, see which one fires.


来源:https://stackoverflow.com/questions/10454134/can-you-ever-alter-the-structure-of-an-indexeddb-database-after-it-has-been-open

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!