From 430e8f18530e3328b116f88c04643308c8156cea Mon Sep 17 00:00:00 2001 From: David Bailey <4248177+davidbailey00@users.noreply.github.com> Date: Tue, 6 Nov 2018 06:54:05 +0900 Subject: [PATCH] fix(gatsby-plugin-offline): Serve the offline shell for short URLs + use no-cors for external resources (#9679) - Fixes the fallback whitelist regex so that short pages match (e.g. `/`), so that these are served offline correctly - Uses `no-cors` mode when caching external resources, so that errors don't appear if the target doesn't allow CORS requests - Allow insecure external resources to be cached for testing on `localhost` Fixes #8145 --- .../gatsby-plugin-offline/src/gatsby-node.js | 4 ++-- .../gatsby-plugin-offline/src/sw-append.js | 20 ++++++++++++------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/gatsby-plugin-offline/src/gatsby-node.js b/packages/gatsby-plugin-offline/src/gatsby-node.js index 874d1da1da3b7..a9f4419e93d21 100644 --- a/packages/gatsby-plugin-offline/src/gatsby-node.js +++ b/packages/gatsby-plugin-offline/src/gatsby-node.js @@ -88,7 +88,7 @@ exports.onPostBuild = (args, pluginOptions) => { // URLs and not any files hosted on the site. // // Regex based on http://stackoverflow.com/a/18017805 - navigateFallbackWhitelist: [/^[^?]*([^.?]{5}|\.html)(\?.*)?$/], + navigateFallbackWhitelist: [/^([^.?]*|[^?]*\.([^.?]{5,}|html))(\?.*)?$/], navigateFallbackBlacklist: [/\?(.+&)?no-cache=1$/], cacheId: `gatsby-plugin-offline`, // Don't cache-bust JS or CSS files, and anything in the static directory @@ -101,7 +101,7 @@ exports.onPostBuild = (args, pluginOptions) => { }, { // Use the Network First handler for external resources - urlPattern: /^https:/, + urlPattern: /^https?:/, handler: `networkFirst`, }, ], diff --git a/packages/gatsby-plugin-offline/src/sw-append.js b/packages/gatsby-plugin-offline/src/sw-append.js index e67dd18cb837b..a578d3708a9e9 100644 --- a/packages/gatsby-plugin-offline/src/sw-append.js +++ b/packages/gatsby-plugin-offline/src/sw-append.js @@ -9,13 +9,19 @@ self.addEventListener(`message`, event => { event.waitUntil( caches.open(cacheName).then(cache => Promise.all( - resources.map(resource => - cache.add(resource).catch(e => { - // ignore TypeErrors - these are usually due to - // external resources which don't allow CORS - if (!(e instanceof TypeError)) throw e - }) - ) + resources.map(resource => { + let request + + // Some external resources don't allow + // CORS so get an opaque response + if (resource.match(/^https?:/)) { + request = fetch(resource, { mode: `no-cors` }) + } else { + request = fetch(resource) + } + + return request.then(response => cache.put(resource, response)) + }) ) ) )