jakearchibald / idb-keyval

A super-simple-small promise-based keyval store implemented with IndexedDB

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using in service worker

jcubic opened this issue · comments

I have really hard time making your library work in Service Worker. The same code that I'm using works fine with BrowserFS (using idendexedBD) but I don't need whole library since I need to host only one file.

I have this code in other worker:

self.addEventListener('install', function(evt) {
    self.skipWaiting();
    self.importScripts('https://cdn.jsdelivr.net/npm/browserfs');
    BrowserFS.configure({ fs: 'IndexedDB', options: {} }, function (err) {
        if (err) {
            console.log(err);
        } else {
            self.fs = BrowserFS.BFSRequire('fs');
            self.path = BrowserFS.BFSRequire('path');
        }
    });
});

ref: https://github.com/jcubic/git/blob/master/sw.js
live: https://jcubic.github.io/git/

And I can stop the worker and use fs module. You can see by cloning the repo (try something small) and calling view (this link will do this for you).

But for unknown reason I can't use idb-keyval library after worker is stoped.

self.addEventListener('install', function(event) {
    self.skipWaiting();
    self.importScripts('https://cdn.jsdelivr.net/npm/idb-keyval/dist/umd.js');
    self.idb = idbKeyval;
});

ref: https://github.com/jcubic/gaiman/blob/master/docs/sw.js
live: https://jcubic.github.io/gaiman/

Here is the question I've asked on StackOverflow:

How to load external script in service worker that will work after stop?

At first the worker was throwing exception, I've change it to return 404 if idb is not defined, and it keeps returning 404 and idb-keyval is still undefined.

Hi @jcubic

I'm using this library in a service worker here. Hopefully this can help you 🙂

@dbrennand I've created this issue long ago, I've already resolved my problem, but forget about this open issue.

The solution is on SO. import need to be in the global context.