Search code examples
service-workerbackground-sync

Service worker sync fires only the first time


On button click I successfully register for sync and it fires the functionality I've described in the service-worker. If I'm offline - it waits for the browser to get connection and then it fires.

BUT - when I click the button the first time and all is fine - from then on clicking the button again successfully registers for sync, but the sync event in the service-worker never triggers:

self.addEventListener('sync', function(event) {
    console.log('EVENT in SYNC', event);
}

I see the console logging only the first time I click the button. Am I missing something?


Solution

  • I figured it out :) ... and the problem was pretty lame: the sync handler in the service worker was returning a promise, but this promise never got resolved. Once I added the resolve() part in the handler returned promise - it all worked fine.

    PS: In the Jake Archibald's demo the sync handler was doing self.registration.showNotification, which returns a promise, and this promise resolves once the notification is shown. On other examples they make simple fetch, which also returns promise, and that promise resolves on success. But on my example - I was pulling data from indexedDB and then making fetch. So - just wrapped everything in

    var p = new Promise(function(resolve, reject) {
        // get data from indexedDB .. 
        fetch(...).then(function(response) {
            return response;
        })
        .then(function() {
            // fetch was successful .. 
            resolve();
        });
    };
    return p;
    

    This way it worked correctly.