diff --git a/templates/workbox/sw.js b/templates/workbox/sw.js index 847ec174..039fd0d7 100644 --- a/templates/workbox/sw.js +++ b/templates/workbox/sw.js @@ -52,6 +52,26 @@ function precacheAssets(workbox, options) { function runtimeCaching(workbox, options) { + const requestInterceptor = { + requestWillFetch({ request }) { + if (request.cache === 'only-if-cached' && request.mode === 'no-cors') { + return new Request(request.url, { ...request, cache: 'default', mode: 'no-cors' }) + } + return request + }, + fetchDidFail(ctx) { + ctx.error.message = + '[workbox] Network request for ' + ctx.request.url + ' threw an error: ' + ctx.error.message + console.error(ctx.error, 'Details:', ctx) + }, + handlerDidError(ctx) { + ctx.error.message = + `[workbox] Network handler threw an error: ` + ctx.error.message + console.error(ctx.error, 'Details:', ctx) + return null + } + } + for (const entry of options.runtimeCaching) { const urlPattern = new RegExp(entry.urlPattern) const method = entry.method || 'GET' @@ -59,6 +79,8 @@ function runtimeCaching(workbox, options) { const plugins = (entry.strategyPlugins || []) .map(p => new (getProp(workbox, p.use))(...p.config)) + plugins.unshift(requestInterceptor) + const strategyOptions = { ...entry.strategyOptions, plugins } const strategy = new workbox.strategies[entry.handler](strategyOptions) diff --git a/test/__snapshots__/pwa.test.js.snap b/test/__snapshots__/pwa.test.js.snap index 6e9fd5a6..1abb6ab0 100644 --- a/test/__snapshots__/pwa.test.js.snap +++ b/test/__snapshots__/pwa.test.js.snap @@ -156,6 +156,26 @@ function precacheAssets(workbox, options) { function runtimeCaching(workbox, options) { + const requestInterceptor = { + requestWillFetch({ request }) { + if (request.cache === 'only-if-cached' && request.mode === 'no-cors') { + return new Request(request.url, { ...request, cache: 'default', mode: 'no-cors' }) + } + return request + }, + fetchDidFail(ctx) { + ctx.error.message = + '[workbox] Network request for ' + ctx.request.url + ' threw an error: ' + ctx.error.message + console.error(ctx.error, 'Details:', ctx) + }, + handlerDidError(ctx) { + ctx.error.message = + \`[workbox] Network handler threw an error: \` + ctx.error.message + console.error(ctx.error, 'Details:', ctx) + return null + } + } + for (const entry of options.runtimeCaching) { const urlPattern = new RegExp(entry.urlPattern) const method = entry.method || 'GET' @@ -163,6 +183,8 @@ function runtimeCaching(workbox, options) { const plugins = (entry.strategyPlugins || []) .map(p => new (getProp(workbox, p.use))(...p.config)) + plugins.unshift(requestInterceptor) + const strategyOptions = { ...entry.strategyOptions, plugins } const strategy = new workbox.strategies[entry.handler](strategyOptions)