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?

  • indexedDB doesn't reset version when you delete a database on Chrome — bug or user error?
  • Exporting and importing IndexedDB data
  • Indexed DB cursor ranges on mulitiple properties
  • Optimized Bulk (Chunk) Upload Of Objects Into IndexedDB
  • IndexedDB with iOS 8/ Safari
  • Getting a “setVersion” is not a function error when using indexedDB
  • 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?

  • Processing a large (12K+ rows) array in JavaScript
  • What difference does the _(underscore) before the function call add() make?
  • How to work with IndexedDB asynchronously?
  • How can I wait until an IndexedDB instance is closed?
  • IndexedDB.open returns null on Safari iOS 8.1.1 and halts execution on Cordova. Even worst on iOS 8.1.2
  • Show video blob after reading it through AJAX
  • One Solution collect form web for “How to persist data in a Service Worker”

    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.