You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单页PWA离线时,如何实现访问非首页展示error.html错误页面?

解决PWA离线访问非首页时展示错误页面的问题

你的原代码存在逻辑问题:caches.match(e.request)在未匹配到缓存资源时,会返回undefined而非抛出错误,因此catch回调不会触发,无法加载error.html。以下是修正后的实现方案:

修正后的Fetch事件代码

self.addEventListener('fetch', e => {
  e.respondWith(
    caches.match(e.request)
      .then(cachedResponse => {
        // 缓存中有匹配资源,直接返回
        if (cachedResponse) {
          return cachedResponse;
        }
        // 缓存无匹配则尝试网络请求
        return fetch(e.request)
          .catch(() => {
            // 网络请求失败(离线状态),返回预缓存的错误页面
            return caches.match('/error.html');
          });
      })
  );
});

关键补充:确保错误页面被缓存

需要在Service Worker的安装阶段,将error.html和index.html一起加入缓存列表,否则离线时无法获取到错误页面:

self.addEventListener('install', e => {
  e.waitUntil(
    caches.open('pwa-cache-v1')
      .then(cache => {
        return cache.addAll([
          '/index.html',
          '/error.html'
          // 可添加其他需要离线访问的静态资源
        ]);
      })
  );
});

逻辑说明

  1. 用户发起请求时,优先检查缓存中是否存在对应资源,存在则直接返回缓存内容
  2. 缓存无匹配时,尝试从网络获取资源
  3. 若网络请求失败(处于离线状态),则返回预缓存的error.html页面

内容的提问来源于stack exchange,提问作者Gerardo J. Cruz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 15:05:26