【问题标题】:Service Worker: Serve offline.html instead when offlineService Worker:离线时提供offline.html
【发布时间】:2019-08-09 22:36:24
【问题描述】:

我正在尝试将我的站点服务人员设置为在离线时显示一个 offline.html 文件,而不是用户尝试获取的不在缓存中的任何 HTML 文件。

按照 Workbox 文档 (https://developers.google.com/web/tools/workbox/guides/advanced-recipes#provide_a_fallback_response_to_a_route),我编写了下面的代码,但是每当我在 Chrome DevTools 中勾选离线复选框并访问 HTML 页面进行测试时,我都会得到 Chrome 的标准“无互联网”恐龙页面。

    workbox.precaching.precacheAndRoute([
        '/offline.html'
    ]);

    workbox.routing.setCatchHandler(({ event }) => {
        switch (event.request.destination) {
            case 'document':
                return caches.match(workbox.precaching.getCacheKeyForURL('/offline.html'));
                break;
            default:
                return Response.error();
        }
    });

【问题讨论】:

    标签: service-worker offline-caching workbox


    【解决方案1】:

    您忘记注册路线。因此,永远不会调用 workbox.routing.setCatchHandler 函数。

    将此代码添加到您的 Service Worker 应该可以解决问题

    workbox.routing.registerRoute(
        new RegExp('.html'),
        new workbox.strategies.NetworkOnly({
            cacheName: 'htmlcache'
        })
    );
    

    你也可以参考这个例子: https://progressify.org/building-a-pwa-with-an-offline-fallback-page-using-workbox/

    【讨论】:

      猜你喜欢
      • 2018-12-12
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 2017-07-18
      • 2017-05-18
      • 2021-01-23
      • 2020-06-09
      • 1970-01-01
      相关资源
      最近更新 更多