带有自定义离线页面的 Angular PWA

标签 angular service-worker angular-pwa

在 Angular (8) 应用程序中,我想添加一个自定义离线页面(只是一个简单的 html 文件)。 我已将我的应用程序设置为 PWA(使用 @angular/pwa 并配置了所有内容,以便它至少在在线时顺利运行)。

但是,我很难为 PWA 用户提供更新。因此,经过几个小时的尝试和错误,我决定从 ngsw-config.json 中排除 index.html。当然,这会产生每次都会加载 index.html 的效果(还不错,因为它太小了)。如果有任何更新 index.html 链接到不同的 JS 文件,这些文件会立即加载。因此,正如我之前所说,PWA 的工作原理正如我所希望的那样。

现在我想在用户离线启动 PWA 时显示 offline.html。因此,我将 offline.html 添加到 ngsw-config.json 中,并创建了一个自定义 Service Worker,其中包括官方 ngsw-worker.js:

importScripts('./ngsw-worker.js');

我也使用这个自定义服务 worker 而不是官方的:

ServiceWorkerModule.register('./custom-worker.js', { enabled: true, registrationStrategy: registrationStrategy })

到目前为止,一切仍然按预期进行。行为举止就跟以前一样。现在我想在我的自定义工作线程中包含离线行为:

importScripts('./ngsw-worker.js');
self.addEventListener('fetch', function(event) {
    return event.respondWith(
      caches.match(event.request)
      .then(function(response) {
        let requestToCache = event.request.clone();

        return fetch(requestToCache).then().catch(error => {
          // Check if the user is offline first and is trying to navigate to a web page
          if (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html')) {
            // Return the offline page
            return caches.match("offline.html");
          }
        });
      })
    );
  });

该脚本来自:https://stackoverflow.com/a/56738140/4653997 不幸的是,这是根本不起作用的部分。现在我几乎陷入困境。我不知道下一步该做什么。 我认为无论 index.html 是否可以加载,Service Worker 都会被执行。

如有任何帮助,我们将不胜感激。

最佳答案

我已经成功了!

最后,这是一个相对简单的 fetch 事件监听器,我必须将其添加到我的自定义服务工作人员中:

// listen to every fetch event
self.addEventListener('fetch', function (event) {
    const request = event.request;
    
    // filter for html document fetches (should only result in one single fetch) --> index.html
    if (request.method === "GET" && request.destination === "document") {

        // only intercept if there was a problem fetching index.html
        event.respondWith(
            fetch(request).catch(function (error) {
                console.error("[onfetch] Failed. Serving cached offline fallback", error);

                // return offline page from cache instead
                return caches.match("/assets/offline.html");
            }));
    }
});

// use all the magic of the Angular Service Worker
importScripts('./ngsw-worker.js');

关于带有自定义离线页面的 Angular PWA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58163206/

相关文章:

angular - rxjs 可观察导入问题

html - 当位置绝对对象移出屏幕时,CSS 隐藏滚动条(在 Angular 6 中)

angular - 服务工作线程不适用于 Azure 静态 Web 应用上的自定义域

progressive-web-apps - Angular PWA 缺少 ngsw.json 和 ngsw-worker 文件

java - 在一个 jar 中使用 Spring boot 2.x 构建 Angular 11

javascript - 如何在 Angular 中制作 ngFor 字典?

php - 将 Laravel 用于服务 worker ?

javascript - 如何在不刷新页面的情况下检测 Service Worker 更新?

google-chrome - chrome.gcm 仅适用于应用程序和扩展程序,我如何将其用作普通网站?

Angular PWA 错误站点无法安装 : no matching service worker detected