2

我目前正在使用最新的 Workbox 版本 4.3.1 workbox-window,我正在通过监听waiting事件为用户提供页面重新加载,我正在使用Workbox 文档的Advanced Recipes页面上提供的代码。

页面上的代码:

if ('serviceWorker' in navigator) {
  const wb = new Workbox('/sw.js');

  // Add an event listener to detect when the registered
  // service worker has installed but is waiting to activate.
  wb.addEventListener('waiting', (event) => {
    // `event.wasWaitingBeforeRegister` will be false if this is
    // the first time the updated service worker is waiting.
    // When `event.wasWaitingBeforeRegister` is true, a previously
    // updated same service worker is still waiting.
    // You may want to customize the UI prompt accordingly.

    // Assumes your app has some sort of prompt UI element
    // that a user can either accept or reject.
    const prompt = createUIPrompt({
      onAccept: async () => {
        // Assuming the user accepted the update, set up a listener
        // that will reload the page as soon as the previously waiting
        // service worker has taken control.
        wb.addEventListener('controlling', (event) => {
          window.location.reload();
        });

        // Send a message telling the service worker to skip waiting.
        // This will trigger the `controlling` event handler above.
        // Note: for this to work, you have to add a message
        // listener in your service worker. See below.
        wb.messageSW({type: 'SKIP_WAITING'});
      },

      onReject: () => {
        prompt.dismiss();
      }
    })
  });

  wb.register();
}

服务工作者文件中的代码:

self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

我已经对其进行了测试,它工作得很好,我可以向用户显示一个小吃栏,让他们知道有更新,当他们接受时,SKIP_WAITING会向服务人员发送一条消息来调用skipWaiting()

假设用户不接受重新加载提示并刷新页面或导航到另一个页面,新的服务人员将一直等待并且不会激活,这是正常行为,但我的问题是如何显示此重新加载提示用户是否刷新或导航到另一个页面?似乎该waiting事件只触发一次。

4

0 回答 0