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

瀏覽器相容性

另見