Skip to content

Commit 430e8f1

Browse files
vtenfysDSchau
authored andcommitted
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
1 parent 864ac04 commit 430e8f1

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

packages/gatsby-plugin-offline/src/gatsby-node.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ exports.onPostBuild = (args, pluginOptions) => {
8888
// URLs and not any files hosted on the site.
8989
//
9090
// Regex based on http://stackoverflow.com/a/18017805
91-
navigateFallbackWhitelist: [/^[^?]*([^.?]{5}|\.html)(\?.*)?$/],
91+
navigateFallbackWhitelist: [/^([^.?]*|[^?]*\.([^.?]{5,}|html))(\?.*)?$/],
9292
navigateFallbackBlacklist: [/\?(.+&)?no-cache=1$/],
9393
cacheId: `gatsby-plugin-offline`,
9494
// Don't cache-bust JS or CSS files, and anything in the static directory
@@ -101,7 +101,7 @@ exports.onPostBuild = (args, pluginOptions) => {
101101
},
102102
{
103103
// Use the Network First handler for external resources
104-
urlPattern: /^https:/,
104+
urlPattern: /^https?:/,
105105
handler: `networkFirst`,
106106
},
107107
],

packages/gatsby-plugin-offline/src/sw-append.js

+13-7
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,19 @@ self.addEventListener(`message`, event => {
99
event.waitUntil(
1010
caches.open(cacheName).then(cache =>
1111
Promise.all(
12-
resources.map(resource =>
13-
cache.add(resource).catch(e => {
14-
// ignore TypeErrors - these are usually due to
15-
// external resources which don't allow CORS
16-
if (!(e instanceof TypeError)) throw e
17-
})
18-
)
12+
resources.map(resource => {
13+
let request
14+
15+
// Some external resources don't allow
16+
// CORS so get an opaque response
17+
if (resource.match(/^https?:/)) {
18+
request = fetch(resource, { mode: `no-cors` })
19+
} else {
20+
request = fetch(resource)
21+
}
22+
23+
return request.then(response => cache.put(resource, response))
24+
})
1925
)
2026
)
2127
)

0 commit comments

Comments
 (0)