首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Workbox service worker手动更新流程

Workbox service worker手动更新流程
EN

Stack Overflow用户
提问于 2020-08-27 18:24:29
回答 1查看 127关注 0票数 1

这是我在react spa中实现的软件注册和刷新。

问题是,当我在当前软件上触发手动更新并接受新版本时(例如,在活动软件中发送post消息SKIP WAITING事件),并且在新软件被激活后,我看不到controlling事件被触发

代码语言:javascript
复制
import { useEffect, useRef } from 'react';
import { Workbox, messageSW } from 'workbox-window';

const SW_PATH = `${process.env.PUBLIC_PATH}sw.js`;

export const useSWRegisterOnMount = (param: {
  createUIPrompt: (opts: { onAccept: () => void }) => void;
}): {
  wb?: InstanceType<typeof Workbox>;
  registration?: ServiceWorkerRegistration;
} => {
  const history = useHistory();

  const wb = useRef<InstanceType<typeof Workbox>>();
  const registration = useRef<ServiceWorkerRegistration>();

  useEffect(() => {
    /** https://developers.google.com/web/tools/workbox/guides/advanced-recipes */
    if ('serviceWorker' in navigator) {
      wb.current = new Workbox(SW_PATH, {
        scope: process.env.PUBLIC_PATH
      });

      const showSkipWaitingPrompt = (): void => {
        param.createUIPrompt({
          onAccept: () => {
            // this works perfectly when app is reopened
            // but in case of manual update service worker(workbox-window?) can skip emitting
            // of this "controlling" (also "activate") event but sw get activated in devtools 
            // application sw panel 
            wb.current?.addEventListener('controlling', () => {
              window.location.reload();
            });

            if (registration.current?.waiting) {
              messageSW(registration.current.waiting, {
                type: 'SKIP_WAITING'
              });
            }
          }
        });
      };

      wb.current.addEventListener('waiting', showSkipWaitingPrompt);
      wb.current.addEventListener('externalwaiting', showSkipWaitingPrompt);

      wb.current.register().then(swRegistration => {
        registration.current = swRegistration;
      });

      // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#manual_updates
      setInterval(() => { // run manual updates
        registration.current?.update().then(() => {
          const sw = registration.current?.installing || registration.current?.waiting;

          if (sw) {
            showSkipWaitingPrompt();
          }
        });
      }, 1000 * 60 * 60);
    }
  }, []);

  return { wb: wb.current, registration: registration.current };
};
EN

回答 1

Stack Overflow用户

发布于 2021-11-16 12:08:10

您应该在服务工作者端处理此事件:

代码语言:javascript
复制
addEventListener('message', (event) => {
    if (event.data.type === 'SKIP_WAITING') {
        skipWaiting();
    }
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63613980

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档