2

In my service worker, I'm implementing background sync with workbox like so

workbox.routing.registerRoute(
    options => options.url.pathname.startsWith('/api/'),
    new workbox.strategies.NetworkOnly({
        plugins: [
            new workbox.backgroundSync.Plugin('myQueueName', {
                maxRetentionTime: 14 * 24 * 60,
                onSync() {
                    showNotification('background sync ran.');
                }
            })]
    }),
    'POST'
);

When I test the behavior by disabling network access, executing a request and then turning network access back on, I'm seeing the notification that is triggered in showNotification, but I'm not seeing the actual requests.

Oddly enough, when I remove the onSync callback, I'm now seeing the requests but obviously, I'm not creating any notifications. How can I get a callback and have the actual requests replayed?

Kirill Rakhman
  • 42,195
  • 18
  • 124
  • 148

1 Answers1

3

I've looked at the implementation of workbox and found the following code:

class Queue {
  ...

  constructor(name, {onSync, maxRetentionTime} = {}) {
    ...
    this._onSync = onSync || this.replayRequests;
...   

and further down

_addSyncListener() {
    if ('sync' in registration) {
      self.addEventListener('sync', (event) => {
          ...

          const syncComplete = async () => {
            this._syncInProgress = true;

            let syncError;
            try {
              await this._onSync({queue: this});

So as it turns out, when you don't pass an onSync callback, the default will be to call replayRequests. If you do pass one, you have to do it yourself, e.g. like so

workbox.routing.registerRoute(
    options => options.url.pathname.startsWith('/api/'),
    new workbox.strategies.NetworkOnly({
        plugins: [
            new workbox.backgroundSync.Plugin('myQueueName', {
                maxRetentionTime: 14 * 24 * 60,
                onSync({ queue }) {
                    // !!! important call here !!!
                    queue.replayRequests(); 
                    showNotification('background sync ran.');
                }
            })]
    }),
    'POST'
);
Kirill Rakhman
  • 42,195
  • 18
  • 124
  • 148