IDBOpenDBRequest

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

注意:此功能在 Web Workers 中可用。

IDBOpenDBRequest 接口是 IndexedDB API 的一部分,它通过特定的事件处理程序属性,提供了对使用 IDBFactory.openIDBFactory.deleteDatabase 执行的打开或删除数据库请求结果的访问。

EventTarget IDBRequest IDBOpenDBRequest

实例属性

还继承了其父接口 IDBRequestEventTarget 的属性。.

实例方法

没有自己的方法,但继承了其父接口 IDBRequestEventTarget 的方法。

事件

IDBRequestEventTarget 等父接口上定义的事件,也可以在 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

浏览器兼容性

另见