vue PWA 是如何使用预缓存的?我仍然得到 "Page does not work offline"

How does vue PWA use the precache? I still get "Page does not work offline"

我有一个 vue 应用程序,我更新后具有 PWA 功能。它使用 firebase 消息服务,该服务已经用自己的 firebase-messaging-sw.js 文件覆盖了 service worker。 service worker 已注册、活跃并正在工作,我在 vue.config.js 文件中添加了 pwa,以便它生成 manifest.json。当您构建应用程序的生产版本时,以下代码将添加到服务工作者的顶部。

importScripts("precache-manifest.7b51ac9589a6dc8041a85d8f1792defa.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");

据我所知,percache 工作正常。

这是否足以让站点在离线模式下运行?

我需要自己添加一些缓存管理吗?

我错过了什么,因为我仍然在 Chrome 的应用程序清单选项卡下的开发工具中收到 "Page does not work offline" 错误消息。

您需要在 serviceworker 中添加这一行。它让浏览器误认为该页面可以离线工作:

self.addEventListener('fetch', function(event) {}) // add this to fool it into thinking its offline ready

看起来 Google 也发现了 quick hack,警告又回来了。

因此自 Chrome93(2021 年 8 月)起,快速破解将不再有效:

self.addEventListener('fetch', function(event) {})

解决方案“暂时”有效(因为我们永远不知道 Google 以后会添加什么要求)

我找到了一篇很好的文章,它提供了一些解决方案,作者提供的第一个是 Network-Falling-Back-To-Cache 策略:

您的服务工作者将首先尝试从您的服务器检索资源。然后当它不能这样做时——因为例如,你处于离线状态——从缓存中检索它(如果它存在)。

   self.addEventListener('fetch', function(event) {
   event.respondWith(async function() {
      try{
        var res = await fetch(event.request);
        var cache = await caches.open('cache');
        cache.put(event.request.url, res.clone());
        return res;
      }
      catch(error){
        return caches.match(event.request);
       }
     }());
 });

您可以在文章中找到所有信息和替代解决方案:

https://javascript.plainenglish.io/your-pwa-is-going-to-break-in-august-2021-34982f329f40

希望这对以后的访客有所帮助。

补充说明:

使用上面的代码你可能会遇到以下错误:

service-worker.js:40 Uncaught (in promise) TypeError: Failed to execute 'put' on 'Cache': Request scheme 'chrome-extension' is unsupported

此错误是由 chrome 扩展(例如 Augury 或 Vue 开发工具)引起的。关闭两者将导致错误消失。