Using following js in my service worker from workboxjs sample for my testing:
importScripts('https://unpkg.com/workbox-sw@0.0.2/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?
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/workbox-runtime-caching@1.3.0');
importScripts('https://unpkg.com/workbox-routing@1.3.0');
importScripts('https://unpkg.com/workbox-background-sync@1.3.0');
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});