Search code examples
workboxbackground-sync

Workbox 4.1 backgroundSync: Queue and Plugin


I need to fetch a token before I can proceed with the background sync, then I'll loop the queue, build a new Request with the token added to the headers and send it.

I'm using the Plugin to register the data submitted offline and it's being registered under workbox-background-sync > requests. The loop while (entry = await queue.shiftRequest()) apparently brings no results as I can't enter the loop, so I'm definitely doing it wrong. Should I move the code from Plugin to Queue (since I need shiftRequest())? If so, how do I make my route register things in the IndexedDB for background sync?

This is what I'm trying:

const queue = new workbox.backgroundSync.Queue();

const bgSyncPlugin = new workbox.backgroundSync.Plugin('bgsync', {
    onSync: async (q) => {
        // this will log
        console.log("Background sync started", q);
        let entry;
        while (entry = await queue.shiftRequest()) {
           // this will never appear in the log
           console.log("Hurray", entry);
        }
     }
 });

workbox.routing.registerRoute(
        new RegExp('/suggestion/post'),
        new workbox.strategies.NetworkOnly({
            plugins: [bgSyncPlugin]
        }),
        'POST'
    );

Solution

  • I faced the same problem. The solution is described here: https://github.com/GoogleChrome/workbox/issues/1982#issuecomment-475645712