如何在chrome扩展中使用IndexedDB?

xdyibdwo  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(1)|浏览(289)

I'm trying to build a chrome extension which uses an IndexedDB. I'm using idb as a wrapper but I'm having errors when creating the initial object stores for the database. My code is as follows:

const DATABASE_NAME = 'PROCRASTINATE_BLOCKER_DATABASE';
const DATABASE_VERSION = 1;
const LINK_OBJECT_STORE = 'link';

setupData(): Promise<void> {
  return openDB(DATABASE_NAME, DATABASE_VERSION).then(db => {
    if (!db.objectStoreNames.contains(LINK_OBJECT_STORE)) {
      db.createObjectStore(LINK_OBJECT_STORE,  { keyPath: 'id', autoIncrement: true });
    }
  });
}

I'm then called the setupData() method in the background.js when the extension gets installed:

chrome.runtime.onInstalled.addListener(details => {
  if(details.reason == 'install' || details.reason == 'update'){
    repositoryOperations.setupData().then(() => alert('stuff'));
  }
});

I also have "store" and "unlimited storage" in my manifest.json file, but honestly don't know if I need it or not.
When I run the extension in the browser I get the following error: Uncaught (in promise) InvalidStateError: Failed to execute 'createObjectStore' on 'IDBDatabase': The database is not running a version change transaction.
I don't understand what I'm doing wrong, I'm following this tutorial and don't get what's wrong. If anybody could help me it would be amazing, thanks in advance.

k3bvogb1

k3bvogb11#

我只需要将代码更改为openDB方法的第三个参数,就像wOxxOm在注解中建议的那样。

setupData(): void {
  openDB(DATABASE_NAME, DATABASE_VERSION, {
    upgrade(db) {
      if (!db.objectStoreNames.contains(LINK_OBJECT_STORE)) {
        db.createObjectStore(LINK_OBJECT_STORE,  { keyPath: 'id', autoIncrement: true });
      }
    }
  })
}

相关问题