W3cubDocs

/Web APIs

IDBTransaction

The IDBTransaction interface of the IndexedDB API provides a static, asynchronous transaction on a database using event handler attributes. All reading and writing of data is done within transactions. You use IDBDatabase to start transactions, IDBTransaction to set the mode of the transaction (e.g. is it readonly or readwrite), and you access an IDBObjectStore to make a request. You can also use an IDBTransaction object to abort transactions.

Note: This feature is available in Web Workers

EventTarget IDBTransaction

Transactions are started when the transaction is created, not when the first request is placed; for example consider this:

js

const trans1 = db.transaction("foo", "readwrite");
const trans2 = db.transaction("foo", "readwrite");
const objectStore2 = trans2.objectStore("foo");
const objectStore1 = trans1.objectStore("foo");
objectStore2.put("2", "key");
objectStore1.put("1", "key");

After the code is executed the object store should contain the value "2", since trans2 should run after trans1.

Transaction failures

Transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort callback:

  • Abort due to bad requests, e.g. trying to add() the same key twice, or put() with the same index key with a uniqueness constraint. This causes an error on the request, which can bubble up to an error on the transaction, which aborts the transaction. This can be prevented by using preventDefault() on the error event on the request.
  • An explicit abort() call from script.
  • An uncaught exception in the request's success/error handler.
  • An I/O error (e.g. an actual failure to write to disk, or other OS/hardware failure).
  • Quota exceeded.
  • A user agent crash.

Firefox durability guarantees

Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see Webkit bug 1112702.) Previously in a readwrite transaction, a complete event was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the complete event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further.

If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see IDBDatabase.transaction.

Instance properties

IDBTransaction.db Read only

The database connection with which this transaction is associated.

IDBTransaction.durability Read only

Returns the durability hint the transaction was created with.

IDBTransaction.error Read only

Returns a DOMException indicating the type of error that occurred when there is an unsuccessful transaction. This property is null if the transaction is not finished, is finished and successfully committed, or was aborted with the IDBTransaction.abort() function.

IDBTransaction.mode Read only

The mode for isolating access to data in the object stores that are in the scope of the transaction. The default value is readonly.

IDBTransaction.objectStoreNames Read only

Returns a DOMStringList of the names of IDBObjectStore objects associated with the transaction.

Instance methods

Inherits from: EventTarget

IDBTransaction.abort()

Rolls back all the changes to objects in the database associated with this transaction. If this transaction has been aborted or completed, this method fires an error event.

IDBTransaction.objectStore()

Returns an IDBObjectStore object representing an object store that is part of the scope of this transaction.

IDBTransaction.commit()

For an active transaction, commits the transaction. Note that this doesn't normally have to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made. commit() can be used to start the commit process without waiting for events from outstanding requests to be dispatched.

Events

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

abort

An event fired when the IndexedDB transaction is aborted. Also available via the onabort property; this event bubbles to IDBDatabase.

complete

An event fired when the transaction successfully completes. Also available via the oncomplete property.

error

An event fired when a request returns an error and the event bubbles up to the connection object (IDBDatabase). Also available via the onerror property.

Mode constants

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Warning: These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. (Firefox bug 888598)

Transactions can have one of three modes:

Constant Value Description
READ_ONLY "readonly" (0 in Chrome)

Allows data to be read but not changed.

READ_WRITE "readwrite" (1 in Chrome) Allows reading and writing of data in existing data stores to be changed.
VERSION_CHANGE "versionchange" (2 in Chrome) Allows any operation to be performed, including ones that delete and create object stores and indexes. Transactions of this mode cannot run concurrently with other transactions. Transactions in this mode are known as "upgrade transactions."

Even if these constants are now deprecated, you can still use them to provide backward compatibility if required (in Chrome the change was made in version 21). You should code defensively in case the object is not available anymore:

js

const myIDBTransaction = window.IDBTransaction ||
  window.webkitIDBTransaction || { READ_WRITE: "readwrite" };

Examples

In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. For a full working example, see our To-do Notifications app (view example live).

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.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db
  // variable. This is used a lot below
  db = DBOpenRequest.result;

  // Add the data to the database
  addData();
};

function addData() {
  // Create a new object to insert 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 to add data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = (event) => {
    note.innerHTML +=
      "<li>Transaction completed: database modification finished.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // 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.oncomplete)
    note.innerHTML += "<li>Request successful.</li>";
  };
}

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
IDBTransaction 2423–57 12 1610–16 10 15 8 ≤37–574.4 2525–57 22 14 8 1.51.5–7.0
abort 23 12 10 10 15 8 4.4 25 22 14 8 1.5
abort_event 23 12 10 10 15 8 4.4 25 22 14 8 1.5
commit 76 79 74 No 63 15 76 76 79 54 15 12.0
complete_event 23 12 10 10 15 8 4.4 25 22 14 8 1.5
db 23 12 10 10 15 8 4.4 25 22 14 8 1.5
durability 83 83 No No 70 15 83 83 No 59 15 13.0
error 23 12 10 10 15 8 4.4 25 22 14 8 1.5
error_event 23 12 10 10 15 8 4.4 25 22 14 8 1.5
mode 23 12 10 10 15 8 4.4 25 22 14 8 1.5
objectStore 23 12 10 10 15 8 4.4 25 22 14 8 1.5
objectStoreNames 48 79 10 No 35 10.1 48 48 22 35 10.3 5.0
worker_support 23 12 37 10 15 10 4.4 25 37 14 10 1.5

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction