IDBOpenDBRequest
注意:此功能在 Web Workers 中可用。
IDBOpenDBRequest 接口是 IndexedDB API 的一部分,它通过特定的事件处理程序属性,提供了对使用 IDBFactory.open 和 IDBFactory.deleteDatabase 执行的打开或删除数据库请求结果的访问。
实例属性
还继承了其父接口 IDBRequest 和 EventTarget 的属性。.
实例方法
没有自己的方法,但继承了其父接口 IDBRequest 和 EventTarget 的方法。
事件
在 IDBRequest 和 EventTarget 等父接口上定义的事件,也可以在 IDBOpenDBRequest 对象上分发。
使用 addEventListener() 或将事件监听器赋值给此接口的 oneventname 属性来监听这些通用和特定的事件。
此接口特定的事件包括:
blocked-
当一个打开的数据库连接正在阻止同一数据库上的
versionchange事务时触发。也可通过onblocked属性访问。 upgradeneeded-
尝试用比当前版本号高的版本号打开数据库时触发。也可通过
onupgradeneeded属性访问。
示例
在以下示例中,您可以看到当加载一个版本号更高的数据库时,如何使用 onupgradeneeded 处理程序来更新数据库结构。要查看完整的可工作示例,请参阅我们的 待办事项通知 应用(在线查看示例)。
js
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
// these event handlers act on the database being opened.
DBOpenRequest.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Error loading database.";
};
DBOpenRequest.onsuccess = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Database initialized.";
// store the result of opening the database in the db
// variable. This is used a lot below
db = DBOpenRequest.result;
// Run the displayData() function to populate the task
// list with all the to-do list data already in the IDB
displayData();
};
// This event handles the event whereby a new version of
// the database needs to be created Either one has not
// been created before, or a new version number has been
// submitted via the window.indexedDB.open line above
// it is only implemented in recent browsers
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Error loading database.";
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
objectStore.createIndex("notified", "notified", { unique: false });
};
规范
| 规范 |
|---|
| Indexed Database API 3.0 # idbopendbrequest |
浏览器兼容性
加载中…
另见
- 使用 IndexedDB
- 开始事务:
IDBDatabase - 使用事务:
IDBTransaction - 设置键的范围:
IDBKeyRange - 检索和修改数据:
IDBObjectStore - 使用游标:
IDBCursor - 参考示例:待办事项通知(查看实时示例)。