Search code examples
javascriptlocal-storageindexeddbweb-workerservice-worker

How to persist data in a Service Worker


As of now, Chrome does not support passing additional data to push notifications received from GCM. So I have to execute a fetch from my Service Worker whenever I receive a push notification. So far, so good.

But: I need to include a request parameter in my http request executed in fetch. How do I tell the service worker my parameter?

What I've tried so far

Using postMessage to tell my Service Worker the request parameter:

var serviceWorkerData = {};

self.addEventListener('message', function (evt) 
{
    console.log('service worker received', evt.data);

    serviceWorkerData = evt.data.myData;
});

self.addEventListener('push', function(event)
{
    event.waitUntil
    (
        fetch("http://my.url", {
            method: 'post',
            body: 'myData=' + serviceWorkerData
        }).then(function(response)
        {
            //...
        })
    );
});

Why this is not working

But this is not persistent, i.e. after I close my browser and open it again, my serviceWorkerData is lost. localStorage is not available within service workers, so how do I get persistence here?


Solution

  • You can use IndexedDB.

    https://github.com/mozilla/localForage if you want a simpler interface for IndexedDB.

    You can import the localForage lib in a service worker using importScripts, see for example: https://github.com/marco-c/mercurius/blob/master/static/sw-push.js.