Search code examples
service-workerprogressive-web-appsbackground-syncworkbox

How to queue post request using workbox?


Using following js in my service worker from workboxjs sample for my testing:

importScripts('https://unpkg.com/[email protected]/build/importScripts/workbox-sw.dev.v0.0.2.js');

I want to try out how to queue the post requests in offline mode using workbox-sw, so once the network is available it process the request from the queue!

Q 1: I think I need to import additional libraries to define my routes for post methods as shown here on github issue #634

How can use import on browser? I tried using importScripts but it doesn't work.

import * as worker from 'workbox-sw';
import 'workbox-routing';

Q 2: Do I need any additional libraries for background sync, so post methods are queued?


Solution

  • I'd recommend using it as part of the larger workbox-sw framework, as a plugin. Here's a version of the sample code, modified to use importScripts() to pull in the Workbox code from a CDN. Alternatively, rather than using the pre-packaged bundles over a CDN, you could use the ES2015 module syntax and then a bundler like Rollup or Webpack to include the relevant code from your local node_modules into the final service worker file.

    importScripts('https://unpkg.com/[email protected]');
    importScripts('https://unpkg.com/[email protected]');
    importScripts('https://unpkg.com/[email protected]');
    
    let bgQueue = new workbox.backgroundSync.QueuePlugin({
      callbacks: {
        replayDidSucceed: async(hash, res) => {
          self.registration.showNotification('Background sync demo', {
            body: 'Product has been purchased.',
            icon: '/images/shop-icon-384.png',
           });
        },
        replayDidFail: (hash) => {},
        requestWillEnqueue: (reqData) => {},
        requestWillDequeue: (reqData) => {},
      },
    });
    
    const requestWrapper = new workbox.runtimeCaching.RequestWrapper({
      plugins: [bgQueue],
    });
    
    const route = new workbox.routing.RegExpRoute({
      regExp: new RegExp('^https://jsonplaceholder.typicode.com'),
      handler: new workbox.runtimeCaching.NetworkOnly({requestWrapper}),
    });
    
    const router = new workbox.routing.Router();
    router.registerRoute({route});