Skip to content

Instantly share code, notes, and snippets.

@jeffposnick
Last active January 4, 2021 12:13
Show Gist options
  • Save jeffposnick/5d2e723f283045e59284d6711f2c8a74 to your computer and use it in GitHub Desktop.
Save jeffposnick/5d2e723f283045e59284d6711f2c8a74 to your computer and use it in GitHub Desktop.
Example Workbox plugin that fallsback to a cached HTML page when there's a non-200 OK navigation response.
export class FallbackOnErrorPlugin {
constructor(fallbackURL) {
this.fallbackURL = fallbackURL;
}
// This is called whenever there's a network response,
// but we want special behavior for non-2xx statuses.
fetchDidSucceed({response}) {
if (response.ok) {
// If it's a 2xx, it can be used as-is.
return response;
}
// This will trigger handlerDidError.
throw new Error(`Invalid response status (${response.status})`);
}
// This callback is new in Workbox v6, and is triggered whenever
// an error (including a NetworkError) is thrown when a handler runs.
handlerDidError() {
return caches.match(this.fallbackURL, {
// Use ignoreSearch as a shortcut to work with precached URLs
// that have _WB_REVISION parameters.
ignoreSearch: true,
});
}
}
import {registerRoute} from 'workbox-routing';
import {NetworkOnly} from 'workbox-strategies';
import {FallbackOnErrorPlugin} from './fallback-on-error-plugin.js';
registerRoute(
// Only trigger this logic for navigation requests for HTML.
({request}) => request.mode === 'navigate',
// Alternatively, use StaleWhileRevalidate, NetworkFirst, etc.
new NetworkOnly({
plugins: [
new FallbackOnErrorPlugin('/fallback.html'),
],
}),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment