简体   繁体   English

更新 service worker (workbox, cra) 后无法通知用户

[英]Can't notify users after updating service worker (workbox, cra)

I'm trying to let user know that the app is updated after installing the new service worker.我试图让用户知道应用程序在安装新服务工作者后已更新。 But the problem is after doing the typical skipWaiting() and ClientsClaim() and trying to send message to clients that there is an update, clients array is empty.但问题是在执行了典型的skipWaiting()ClientsClaim()并尝试向客户端发送有更新的消息后, clients数组为空。

index.js索引.js

serviceWorkerRegistration.Register();

serviceWorkerRegistration.js serviceWorkerRegistration.js


function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === "installed") {
            if (navigator.serviceWorker.controller) {
              // here workbox sends message to service-worker.js
              registration.waiting.postMessage({ type: "SKIP_WAITING" });

              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error("Error during service worker registration:", error);
    });
}

service-worker.js service-worker.js

self.addEventListener("message", event => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    skipWaiting();
    clientsClaim();
    //clients array is empty here
    self.clients.matchAll().then(clients => {
       clients.forEach(client => {
        client.postMessage("reload-window");
      });
    });
  }
});

Clients array is empty in service-worker.js , That being the case, I can't communicate with user. service-worker.js中的 Clients 数组为空,这样就无法与用户通信了。

(I've also setup notifications with this service worker, Clients array is not empty there as a result I've no problem communicating with user) (我还为这个服务工作者设置了通知,客户端数组在那里不为空,因此我与用户沟通没有问题)

Any help is greatly appreciated.任何帮助是极大的赞赏。

I was able to reproduce the problem.我能够重现这个问题。

Should've been doing this part:应该一直在做这部分:

self.clients.matchAll().then(clients => {
       clients.forEach(client => {
        client.postMessage("reload-window");
      });
    });

while listening to activate event like this:在听这样的activate事件时:

self.addEventListener("activate", () => {
  self.clients.matchAll().then(clients => {
    clients.forEach(client => {
      client.postMessage("reload-window");
    });
  });
});

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

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