繁体   English   中英

我可以在服务人员中捕获 404 吗?

[英]Can I catch 404s in a service worker?

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

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

这在网上很好用,但是当页面离线时,我可以使用 ServiceWorker 来支持这个文件夹/文件 model 吗? 或者,除非我明确缓存 URL,否则我是否总是会出现找不到页面的错误?

您所描述的可以使用应用程序 Shell model来完成。

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

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 处于控制状态时,应用程序 Shell HTML 将用于完成所有导航请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM