Skip to content

Commit

Permalink
fix(gatsby-plugin-offline): Serve the offline shell for short URLs + …
Browse files Browse the repository at this point in the history
…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
  • Loading branch information
valin4tor authored and DSchau committed Nov 5, 2018
1 parent 864ac04 commit 430e8f1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
4 changes: 2 additions & 2 deletions packages/gatsby-plugin-offline/src/gatsby-node.js
Expand Up @@ -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
Expand All @@ -101,7 +101,7 @@ exports.onPostBuild = (args, pluginOptions) => {
},
{
// Use the Network First handler for external resources
urlPattern: /^https:/,
urlPattern: /^https?:/,
handler: `networkFirst`,
},
],
Expand Down
20 changes: 13 additions & 7 deletions packages/gatsby-plugin-offline/src/sw-append.js
Expand Up @@ -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))
})
)
)
)
Expand Down

0 comments on commit 430e8f1

Please sign in to comment.