我可以在 Service Worker 中捕获 404 吗?

Can I catch 404s in a service worker?

基本上,我有一个在线应用程序,它使用 htaccess 文件静默地将给定 /folder/ 中的所有请求重定向到相同的 html。然后,为了决定向用户展示什么,页面调用

var page_name = location.href.split('/').pop();

这在线上运行良好,但我可以在页面离线时使用 ServiceWorker 来支持此 folder/file 模型吗?或者除非我显式缓存 URL,否则我总是会收到找不到页面的错误吗?

您所描述的可以使用 App Shell model 来完成。

您的 service worker 的确切代码可能看起来有点不同,像 Workbox 这样的工具可以为您自动执行其中的一些操作,但是一个非常基本的 service worker 完成此操作的“普通”示例是:

self.addEvenListener('install', (event) => {
  const cacheShell = async () => {
    const cache = await caches.open('my-cache');
    await cache.add('/shell.html');
  };

  event.waitUntil(cacheShell());
});

self.addEventListener('fetch', (event) => {
  // If this is a navigation request...
  if (event.request.mode === 'navigate') {
    // ...respond with the cached shell HTML.
    event.respondWith(caches.match('/shell.html'));
    return;
  }

  // Any other caching/response logic can go here.
});

无论 location.href 值是多少,当这个 service worker 处于控制之下时,App Shell HTML 将用于完成所有导航请求。