Search code examples
sqlitegoogle-chrome-extensionwebassembly

Saving to SQLite from Chrome Extension


There is a new JSWASM approach that allows saving to SQLite (the fast OPFS way) in the browser via a javascript Worker. A sample is here that is (sort of) for a Chrome extension. Ideally, it would allow saving from the background.js, but it's unclear whether a worker can be called from there in MV3 based on this and this. Does anyone have a simple working example closer to my use case, which is saving content from the user's active tab to a SQLite database? Thanks.


Solution

  • The OPFS depends on the createSyncAccessHandle() method, which is exposed in Worker threads. The usual feature detection goes like this:

    if (self instanceof WorkerGlobalScope && 'createSyncAccessHandle' in self.FileSystemFileHandle.prototype) {
      // OPFS in `Worker` is supported!
    }
    

    Now an extension service worker (as currently implemented in Chrome) is an instance of ServiceWorkerGlobalScope, so the API is not supported there.

    Unfortunately at the moment the only choice is to open an extension page and then run the OPFS code from there.