IDBTransaction: mode 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

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

IDBTransaction 介面的只讀屬性 mode 返回事務範圍內用於訪問物件儲存區中資料的當前模式(即,模式是要只讀,還是要寫入物件儲存區?)。預設值為 readonly

一個定義當前物件儲存區資料訪問隔離模式的物件:一個定義當前物件儲存區資料訪問隔離模式的字串。可用值如下:

readonly

允許讀取資料但不能更改。

readwrite

允許讀取和寫入現有資料儲存區中的資料。

versionchange

允許執行任何操作,包括刪除和建立物件儲存區及索引的操作。此模式用於在呼叫 IDBFactory.open() 時檢測到版本號更新的需求。此模式的事務不能與其他事務併發執行。此模式下的事務稱為升級事務

示例

在以下程式碼段中,我們打開了一個數據庫的讀/寫事務,並將一些資料新增到物件儲存區。還要注意事務事件處理程式上附加的函式,用於在事務開啟成功或失敗時報告其結果。最後,我們使用 mode 記錄當前事務的模式。有關完整的可執行示例,請參閱我們的 待辦事項通知應用程式檢視即時示例)。

js
const note = document.getElementById("notifications");

// an instance of a db object for us to store the IDB data in
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

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 addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready for being inserted into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      "Transaction completed: database modification finished.";
  };

  transaction.onerror = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      "Transaction not opened due to error. Duplicate items not allowed.";
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");

  // add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of the request (this does not mean the item
    // has been stored successfully in the DB - for that you need transaction.onsuccess)
    note.appendChild(document.createElement("li")).textContent =
      "Request successful.";
  };

  // Return the mode this transaction has been opened in (should be "readwrite" in this case)
  transaction.mode;
}

規範

規範
Indexed Database API 3.0
# ref-for-dom-idbtransaction-mode①

瀏覽器相容性

另見