From 7ba8ec548bfd1801662b0246d6dbcd4875e6a671 Mon Sep 17 00:00:00 2001 From: David Bailey Date: Sat, 3 Nov 2018 11:41:04 +0000 Subject: [PATCH] fix(gatsby-plugin-offline): Use no-cors for external resources --- .../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)) + }) ) ) )