我正在尝试使用indexedDB存储一些数据客户端,并且我无法正确设置数据库。
我正在关注教程here
第一次安装扩展程序时会触发onupgradeneeded()
事件 ,但由于某种原因,没有与对象存储事务关联的事件被触发,而且我无法找到解决此问题的任何文档。
这是相关代码:
const db_name="Tags";
var request = window.indexedDB.open(db_name, 1);
var tags = [
//codes: 0 - markdown wrap tag
// 1 - HTML wrap tag
// 2 - single tag
{ domain: "www.youtube.com",
bold:["*",0],
strikethrough:["-",0],
italic:["_",0]
},
{ domain: "www.stackoverflow.com",
bold:["<strong>",1],
italic:["<em>",1],
strikethrough:["<del>",1],
superscript:["<sup>",1],
subscript:["<sub>",1],
heading1:["<h1>",1],
heading2:["<h2>",1],
heading3:["<h3>",1],
blockquote:["<blockquote>",1],
code:["<code>",1],
newline:["<br>",2],
horizontal:["<hr>",2]
}
];
request.onerror = function(event) {
alert("Error opening the database");
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("domains", {keyPath: "domain" });
objectStore.createIndex("domain", "domain", { unique: true });
alert("I'm trying to do stuff");
objectStore.transaction.oncomplete = function(event) {
var domanStore=db.transaction("domains","readwrite").objectStore("domains");
for(var i in tags)
{
domainStore.add(tags[i]);
alert("added " + tags[i]["domain"] + " to the DB");
}
alert("I might have done stuff");
};
objectStore.transaction.onerror = function(event) {
alert("Transaction error");
};
objectStore.transaction.onabort = function(event){
alert("Transaction aborted");
};
db.onerror=function(event){
alert("DB ERROR bubbled up");
};
alert("I thought I did something");
};
弹出的唯一提示框是
我试图做的事情。
和
我以为我做了些什么。
控制台显示没有错误。
我唯一能想到的是我没有正确创建对象存储,但我无法看到我在这里做错了什么。
其他一些有用的资料来源:
答案 0 :(得分:1)
你可以使用这样的东西 -
const db_name="Tags";
var request = window.indexedDB.open(db_name, 1);
var tags = [
//codes: 0 - markdown wrap tag
// 1 - HTML wrap tag
// 2 - single tag
{ domain: "www.youtube.com",
bold:["*",0],
strikethrough:["-",0],
italic:["_",0]
},
{ domain: "www.stackoverflow.com",
bold:["<strong>",1],
italic:["<em>",1],
strikethrough:["<del>",1],
superscript:["<sup>",1],
subscript:["<sub>",1],
heading1:["<h1>",1],
heading2:["<h2>",1],
heading3:["<h3>",1],
blockquote:["<blockquote>",1],
code:["<code>",1],
newline:["<br>",2],
horizontal:["<hr>",2]
}
];
request.onerror = function(event) {
alert("Error opening the database");
};
request.onupgradeneeded = function(event)
{
var db = event.target.result;
var objectStore = db.createObjectStore("domains", {keyPath: "domain" });
objectStore.createIndex("domain", "domain", { unique: true });
alert("I'm trying to do stuff");
for(var i in tags)
{
objectStore.add(tags[i]);
alert("added " + tags[i]["domain"] + " to the DB");
}
alert("I might have done stuff");
alert("I thought I did something");
};
由于您在创建objectStore时填充数据,因此您不必在onupgradeneeded函数中创建事务,在此函数之外您必须创建事务