Search code examples
angularservice-workerprogressive-web-appsbackground-sync

Background Sync not triggering automatically


Ok, so I'm trying to make an Angular 7 PWA that uses background sync.

I can trigger the sync event from within the dev tools in Chromium but it won't trigger when I remove my ethernet cable and plug it back in.

I originally thought it was my service worker file being odd so I added this: https://stackoverflow.com/a/50414028/9978023 , what's weird is that it works in Firefox but not Chromium. So using this I can trigger the same function that the sync event is meant to call. But it's not a great solution.

self.addEventListener('sync', function (event) {
  console.log('I heard a sync event. Sending Posts to server', event);
  event.waitUntil(sendPostsToServer()
    .then(res => {
      console.log(res);
    })
    .catch(e=>{console.log(e)}));
});


async function sendPostsToServer() {
  // POST to server
}

service-worker.js

What am I doing wrong? Why isn't the sync event triggering when I reconnected to the Internet?


Solution

  • I figured out what was going on. I had to manually tell the Service Worker to trigger the sync event when it was back online with:

    navigator.serviceWorker.ready.then(function (swRegistration) {
         return swRegistration.sync.register('myFirstSync');
    });
    

    With this (which i run when the POST is unsuccessful) the SW will run trigger the sync event when we're back online.

    P.S. This will only trigger the event once:

    If you go back online after running the code above it will trigger but if you go back off and back on afterwards it will not trigger again. So this code needs to be ran every time you want the background sync to work.