How to run function in background with service worker

Viewed 2903

I am building a javascript Web Application. In there i want to upload pictures and other data to a server. This is all working, but i want to use the application offline as well. Therefore i implemented the indexedDB, to store the data offline. Furthermore i made a sync-function, which will be executed every 5 seconds (setIntervall()...) to syncronise the data to the server if there is a internet connection again.

The problem is, that this sync-function only works when the app is open. So I researched a method to solve my problem and i got the idea of a "service worker" with background sync.

The problem is i don't know how to implement it.

This is what i currently have (the whole app is programmed in MVC-concept):

  • I have a sw.js with the following code:
  if (event.tag == 'myFirstSync') {
    event.waitUntil(sync());
  }
});
  • In the controller there is the function sync() for synchronising the data
1 Answers

You can implement your background sync inside of your sw.js file, in the handler for the 'sync' event:

self.addEventListener('sync', function(event) {
  if (event.tag == 'myFirstSync') {
    event.waitUntil(() => {
      // Put your sync code here.
    });
  }
});

At some point after you register your service worker, you need to trigger a sync:

// Register your service worker:
navigator.serviceWorker.register('/sw.js');

// Then later, request a one-off sync:
navigator.serviceWorker.ready.then(function(swRegistration) {
  return swRegistration.sync.register('myFirstSync');
});

After triggering the sync once, if it fails, the sync should keep on retrying on its own (even if the app is not open in the browser).

If it fails, another sync will be scheduled to retry. Retry syncs also wait for connectivity, and employ an exponential back-off.

See https://developers.google.com/web/updates/2015/12/background-sync for further details.

Related