IDBDatabase: close 事件
当数据库连接意外关闭时,close
事件将在 IDBDatabase
上触发。例如,如果底层存储被移除,或者用户在浏览器的历史偏好设置中清除了数据库,就会发生这种情况。
请注意,如果使用 IDBDatabase.close()
正常关闭数据库连接,则不会触发该事件。
语法
在诸如 addEventListener()
之类的函数中使用事件名称,或者设置事件处理程序属性。
js
addEventListener("close", (event) => {});
onclose = (event) => {};
事件类型
一个通用的 Event
。
示例
此示例打开数据库并监听 close
事件
js
// Open the database
const dBOpenRequest = window.indexedDB.open("toDoList", 4);
dBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
// 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 });
};
dBOpenRequest.onsuccess = (event) => {
const db = dBOpenRequest.result;
db.addEventListener("close", () => {
console.log("Database connection closed");
});
};
相同的示例,使用 onclose
属性而不是 addEventListener()
js
// Open the database
const dBOpenRequest = window.indexedDB.open("toDoList", 4);
dBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
// 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 });
};
dBOpenRequest.onsuccess = (event) => {
const db = dBOpenRequest.result;
db.onclose = () => {
console.log("Database connection closed");
};
};
浏览器兼容性
BCD 表仅在启用 JavaScript 的浏览器中加载。