IndexedDB 的 getAll 接口可一次性获取对象存储中所有记录,但仅支持 Chrome 75+、Firefox 75+、Safari 15.4+,且必须在活跃只读事务中调用,不支持参数筛选,大数据量时宜用 openCursor 分批处理。

IndexedDB 的 getAll 接口可以一次性获取对象存储(object store)中的所有记录,但需注意它只在较新版本的浏览器中支持(Chrome 75+、Firefox 75+、Safari 15.4+),且必须在事务活跃状态下调用。
确认浏览器兼容性与打开数据库
使用 getAll 前先检查是否可用,并确保数据库已正确打开:
- 用
indexedDB.open("dbName", version)打开或升级数据库 - 在
onupgradeneeded中创建 object store(如未存在) - 确保目标 object store 已启用
autoIncrement或有明确 key path,但这对getAll非必需
在读写事务中调用 getAll
getAll 必须在 active transaction 内执行,不能在数据库打开后直接调用。典型写法如下:
const request = db.transaction("users", "readonly")
.objectStore("users")
.getAll();
request.onsuccess = function(event) {
const allRecords = event.target.result; // 数组,包含所有匹配记录
console.log(allRecords);
};
request.onerror = function(event) {
console.error("获取全部数据失败:", event.target.error);
};
注意:getAll() 不接受参数,会返回该 object store 中所有记录(按主键升序排列);若需带条件筛选,应改用 openCursor 或 get + 索引组合。
立即学习“Java免费学习笔记(深入)”;
处理大量数据时的注意事项
getAll 会把全部数据加载进内存,不适合海量记录(例如数万条以上):
- 内存占用高,可能触发浏览器警告或崩溃
- 无分页、无流式读取能力,无法中断或暂停
- 如需遍历大数据集,推荐用
openCursor分批处理
替代方案:兼容旧版浏览器
若需支持 Safari 15.3 或更早版本(不支持 getAll),可用游标手动收集:
const store = db.transaction("users", "readonly").objectStore("users");
const results = [];
const cursorRequest = store.openCursor();
cursorRequest.onsuccess = function(event) {
const cursor = event.target.result;
if (cursor) {
results.push(cursor.value);
cursor.continue();
} else {
console.log("全部数据:", results);
}
};
这种方式兼容性更好,逻辑也更可控,只是代码略长。


















