首页 文章

转储indexedDB数据

提问于
浏览
0

使用Chrome扩展程序,需要与IndexedDB集成 . 试图弄清楚如何使用 Dexie.JS . 找到了一堆样品 . 那些看起来并不太复杂 . 有一个特别的例子对于与Dexie在https://github.com/dfahlander/Dexie.js/blob/master/samples/open-existing-db/dump-databases.html探索IndexedDB特别有趣 .

但是,当我运行上面的那个 - "dump utility,"时,它没有看到IndexedDB数据库,告诉我: There are databases at the current origin.

从开发人员工具 Application 选项卡的Storage下,我看到了我的 IndexedDB 数据库 .

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

我应该看什么?

谢谢

1 回答

  • 0

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

    对于铬浏览器,Dexie.getDatabaseNames()将列出当前来源的所有数据库,但对于非铬浏览器,仅显示使用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);
    })();
    

相关问题