React PWA Workbox InvalidStateError

问题描述 投票:0回答:0

IOS 设备上的少数用户出现错误

InvalidStateError
newestWorker is null
.

这是我使用 workbox-window 的注册功能,就像提到的文档一样

 if ('serviceWorker' in navigator) {
    const wb = new Workbox(`${process.env.PUBLIC_URL}/service-worker.js`)
    const showSkipWaitingPrompt = async (event) => {
        wb.addEventListener('controlling', () => {
            window.location.reload()
        })
        wb.messageSkipWaiting()
    }
    wb.addEventListener('waiting', (event) => {
        showSkipWaitingPrompt(event)
    })
    wb.register()
}

我在 index.js(主文件)的顶层调用它

我就是这样称呼更新的:

const updateVersion = () => {
    navigator.serviceWorker?.getRegistrations().then((registrations) => {
        try {
            for (const reg of registrations) {
                reg.update()
            }
        } catch (error) {
            if (error.name !== 'InvalidStateError') {
                throw error   // here should be better error handling
            }
        }
    })
}

 const { pathname } = useLocation()   // from react-router-dom
 useEffect(() => {
     updateVersion()
 }, [pathname])

这就是我的 service worker 中的内容

import { clientsClaim } from 'workbox-core'
import { ExpirationPlugin } from 'workbox-expiration'
import { precacheAndRoute, createHandlerBoundToURL, cleanupOutdatedCaches } from 'workbox-precaching'
import { registerRoute } from 'workbox-routing'
import { StaleWhileRevalidate } from 'workbox-strategies'

clientsClaim();
cleanupOutdatedCaches();
precacheAndRoute((self as any).__WB_MANIFEST);
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
    ({ request, url }) => {
        if (request.mode !== 'navigate') {
            return false;
        }

        if (url.pathname.startsWith('/_')) {
            return false;
        }

        if (url.pathname.match(fileExtensionRegexp)) {
            return false;
        } 

        return true;
    },
    createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);

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

为什么会发生这个错误,我该如何预防/处理它?我应该以某种方式注销并重新注册软件吗?

  • Workbox 版本 6.5.3
  • 反应版本:18.2.0

不存在有关错误的更多信息。

reactjs progressive-web-apps workbox workbox-window
© www.soinside.com 2019 - 2024. All rights reserved.