【问题标题】:Dumping indexedDB data转储 indexedDB 数据
【发布时间】:2018-02-12 00:31:13
【问题描述】:

正在开发需要与 IndexedDB 集成的 Chrome 扩展程序。试图弄清楚如何使用Dexie.JS。找到一堆样本。这些看起来并不太复杂。在https://github.com/dfahlander/Dexie.js/blob/master/samples/open-existing-db/dump-databases.htmlhttps://github.com/dfahlander/Dexie.js/blob/master/samples/open-existing-db/dump-databases.html 有一个与 Dexie 一起探索 IndexedDB 的具体示例。

但是,当我运行上面的“转储实用程序”时,它看不到 IndexedDB 数据库,告诉我:There are databases at the current origin.

从开发者工具Application 选项卡的存储下,我看到了我的IndexedDB 数据库。

这是某种权限问题吗?任何选项卡/用户都可以访问任何 indexedDB 数据库吗?

我应该看什么?

谢谢

【问题讨论】:

  • 扩展的自己的页面有自己的来源。内容脚本使用网页来源。

标签: javascript google-chrome-extension indexeddb dexie


【解决方案1】:

在 chrome/opera 中,有一个非标准 API webkitGetDatabaseNames(),Dexie.js 使用它来检索当前来源的数据库名称列表。对于其他浏览器,Dexie 通过为每个来源保持最新的数据库名称来模拟此 API,因此:

对于 chromium 浏览器,Dexie.getDatabaseNames() 将列出当前来源的所有数据库,但对于非 chromium 浏览器,只会显示使用 Dexie 创建的数据库。

如果您需要转储每个数据库的内容,请查看this issue,它基本上给出了:

interface TableDump {
    table: string
    rows: any[]
}

function export(db: Dexie): TableDump[] {
    return db.transaction('r', db.tables, ()=>{
        return Promise.all(
            db.tables.map(table => table.toArray()
                .then(rows => ({table: table.name, rows: rows})));
    });
}

function import(data: TableDump[], db: Dexie) {
    return db.transaction('rw', db.tables, () => {
        return Promise.all(data.map (t =>
            db.table(t.table).clear()
              .then(()=>db.table(t.table).bulkAdd(t.rows)));
    });
}

将这些函数与 JSON.stringify() 和 JSON.parse() 结合使用以完全序列化数据。

const db = new Dexie('mydb');
db.version(1).stores({friends: '++id,name,age'});

(async ()=>{
    // Export
    const allData = await export (db);
    const serialized = JSON.stringify(allData);

    // Import
    const jsonToImport = '[{"table": "friends", "rows": [{id:1,name:"foo",age:33}]}]';
    const dataToImport = JSON.parse(jsonToImport);
    await import(dataToImport, db);
})();

【讨论】:

猜你喜欢
  • 2017-09-05
  • 2012-02-25
  • 1970-01-01
  • 2019-04-06
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多