2017-09-03 61 views
0

使用需要與IndexedDB集成的Chrome擴展。試圖弄清楚如何使用Dexie.JS。發現了一堆樣品。這些看起來不太複雜。有一個具體的例子特別有趣在https://github.com/dfahlander/Dexie.js/blob/master/samples/open-existing-db/dump-databases.html傾銷indexedDB數據

然而,隨着Dexie探索IndexedDB的,當我運行上面的一個 - 「轉儲程序」,它不會看到IndexedDB的數據庫,告訴我:There are databases at the current origin.

從開發人員工具Application選項卡下的存儲,我看到我的IndexedDB數據庫。

這是某種權限問題?任何標籤/用戶都可以訪問任何indexedDB數據庫嗎?

我該看什麼?

謝謝

+2

擴展自己的頁面有其自己的起源。內容腳本使用網頁來源。 – wOxxOm

回答

0

在鍍鉻/歌劇,有一個非標準的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); 
})();