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①

浏览器兼容性

另见