The transaction read-only property of the IDBRequest interface returns the transaction for the request, that is, the transaction the request is being made inside.
This property can be null for requests not made within transactions, such as for requests returned from IDBFactory.open — in this case you're just connecting to a database, so there is no transaction to return. If a version upgrade is needed when opening a database then during the upgradeneeded event handler the transaction property will be an IDBTransaction with mode equal to "versionchange", and can be used to access existing object stores and indexes, or abort the upgrade. Following the upgrade, the transaction property will again be null.
The following example requests a given record title, onsuccess gets the associated record from the IDBObjectStore (made available as objectStoreTitleRequest.result), updates one property of the record, and then puts the updated record back into the object store in another request. The source of the requests is logged to the developer console — both originate from the same transaction. For a full working example, see our To-do Notifications app (View the example live).
const title = "Walk dog";
const objectStore = db
.transaction(["toDoList"], "readwrite")
.objectStore("toDoList");
const objectStoreTitleRequest = objectStore.get(title);
objectStoreTitleRequest.onsuccess = () => {
const data = objectStoreTitleRequest.result;
data.notified = "yes";
const updateTitleRequest = objectStore.put(data);
console.log(
`The transaction that originated this request is ${updateTitleRequest.transaction}`,
);
updateTitleRequest.onsuccess = () => {
displayData();
};
};
This example shows how a the transaction property can be used during a version upgrade to access existing object stores:
const openRequest = indexedDB.open("db", 2);
console.log(openRequest.transaction);
openRequest.onupgradeneeded = (event) => {
console.log(openRequest.transaction.mode);
const db = openRequest.result;
if (event.oldVersion < 1) {
db.createObjectStore("books");
}
if (event.oldVersion < 2) {
const bookStore = openRequest.transaction.objectStore("books");
bookStore.createIndex("by_title", "title");
}
};
openRequest.onsuccess = () => {
console.log(openRequest.transaction);
};