Safari和iPhone网络浏览器似乎无法允许用户从单独的交易中创建不同的对象存储。当用户关闭数据库,增加版本号,然后在onupgradedneeded回调中使用createObjectStore()时,情况就是如此。
有解决方法吗?
例如,访问Safari中的http://bl.ocks.org/redgeoff/1dea140c52397d963377,当Safari尝试创建第二个对象库时,您将收到带有“AbortError”的警报。
为方便起见,这里是相同的代码片段:
var idb = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB
|| window.msIndexedDB;
// Generate a unique db name as IndexedDB is very delicate and we want our test
// to focus on a new DB
var dbName = 'mydb' + '_' + (new Date()).getTime() + '_'
+ Math.round(1000000*Math.random());
var db = null;
var version = 1;
var open = function (version, onSuccess, onUpgradeNeeded) {
var request = null;
if (version) {
request = idb.open(dbName, version);
} else { // 1st time opening?
request = idb.open(dbName);
}
request.onupgradeneeded = function () {
if (onUpgradeNeeded) {
onUpgradeNeeded(request);
}
};
request.onsuccess = function () {
db = request.result;
if (onSuccess) {
onSuccess(request);
}
};
request.onerror = function () {
console.log('error=', request.error);
alert('error=' + JSON.stringify(request.error));
};
};
var createObjectStore = function (name, callback) {
db.close(); // synchronous
version++; // increment version to trigger onupgradeneeded
open(version, callback, function (request) {
request.result.createObjectStore(name, {
keyPath: 'id'
});
});
};
// NOTE: we could create the first store when opening the DB for the first time, but we'll keep
// things simple and reuse our createObjectStore code for both object stores
open(null, function () {
createObjectStore('store1', function () {
createObjectStore('store2', function () {
console.log('done creating both stores');
});
});
});
在关闭数据库并重新打开后,我尝试使用2秒钟的休眠时间,但似乎无法正常工作。如果没有解决方法,那么这实际上意味着您无法在Safari中使用IndexedDB实现来动态创建对象存储,这意味着您需要在创建数据库之前了解所有对象存储。
答案 0 :(得分:0)
除非我弄错了并且有人有解决方法,否则动态添加对象存储的最佳方法是实现db-per-object-store设计。换句话说,您应该在需要创建新对象库时创建新数据库。
另一个好的选择是使用https://github.com/axemclion/IndexedDBShim使用WebSQL模拟IndexedDB。