简体   繁体   English

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

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

Basically, I have an online app that uses a htaccess file to silently redirect all requests in a given /folder/ to the same html.基本上,我有一个在线应用程序,它使用 htaccess 文件将给定 /folder/ 中的所有请求静默重定向到同一个 html。 Then, to decide what to show the user, the page calls然后,为了决定向用户展示什么,页面调用

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

This works well online, but could I use a ServiceWorker to support this folder/file model while the page is offline?这在网上很好用,但是当页面离线时,我可以使用 ServiceWorker 来支持这个文件夹/文件 model 吗? Or will I always get the page cannot be found error unless I explicitly cache the URLs?或者,除非我明确缓存 URL,否则我是否总是会出现找不到页面的错误?

What you describe can be accomplished using the App Shell model .您所描述的可以使用应用程序 Shell model来完成。

Your service worker's exact code might look a little different, and tools like Workbox can automate some of this for you, but a very basic, "vanilla" example of a service worker that accomplishes this is:您的服务工作者的确切代码可能看起来有点不同,像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.
});

Regardless of what the location.href value is, when this service worker is in control, the App Shell HTML will be used to fulfill all navigation requests.无论location.href的值是多少,当这个 service worker 处于控制状态时,应用程序 Shell HTML 将用于完成所有导航请求。

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

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