我的服务人员有一个用例,在某些情况下,我需要重新加载页面或重定向页面。
-
目前,我们将服务工作者用作所有导航获取的拦截器。因此,在激活服务人员时重新加载页面非常重要。我现在是在
activated
活动本身:
function getClientList(): Promise<readonly WindowClient[]> {
return self.clients.claim().then(() =>
self.clients.matchAll({
type: 'window'
})
);
}
self.addEventListener('activate', async (event: ExtendableEvent) => {
console.log('Service Worker activated');
// we need to reload the page here so that the navigation fetch request is caught
const clientList = await getClientList();
for (const client of clientList) {
const url = new URL(client.url);
await client.navigate(`${url.pathname}${url.search}`);
}
});
这似乎没有任何问题,我只是担心这是否是最好的方法。
-
第二个条件是,当服务人员的导航获取事件中的url包含某个查询参数时,我需要重定向用户。
async function handleNavigationRequest(request: Request, workerLocation: WorkerLocation): Promise<Response> {
const requestURL = new Url(request.url)
const lid = requestURL.searchParams.get('lid');
const code = requestURL.searchParams.get('code');
const optin = requestURL.searchParams.get('optin');
const dpp = !!rbdsCode && !!loyaltyId && !!optin;
if (dppRequest) {
const clientList = await getClientList();
for (const client of clientList) {
const url = new URL(`https://some-domain.com/#/getTokens?brand=${BRAND}&code=${code}&lid=${loyaltyId}&optin=${optin}&env=${DPP_SSO_ENV}`);
await client.navigate(url);
}
}
}
self.addEventListener('fetch', (event) => {
if (event.request.method === 'GET' && event.request.mode === 'navigate') {
event.respondWith(
handleNavigationRequest(event.request, self.location)
);
}
});
第二部分是部分工作。似乎在第一次激活服务工作者时,它会按照步骤1中的预期重新加载页面,然后在步骤2中选择正确的查询参数并执行重定向。
然而,如果我只是在服务工作者已经激活的实例上使用相同的查询参数运行一个请求,我会在控制台中收到一个错误,声明。。。
Uncaught (in promise) TypeError: Cannot navigate to URL: https://some-domain.com/#/getTokens?brand=someBrand&code=572896&lid=7Rewards&optin=Y&env=dev