I have a use case with my service worker where on certain occasions I need to either reload the page, or redirect the page.
activated event as such: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}`);
}
});
This seems to be working without any issues, I am just concerned as to whether this is the best approach.
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)
);
}
});
This second part is partially working. It seems the first time the service worker is activated, it reloads the page as expected in step 1, and then picks up the correct query params in step 2 and performs the redirect.
However if I simply run a request with the same query params on an instance where the service worker has already been activated, I get an error in my console stating...
Uncaught (in promise) TypeError: Cannot navigate to URL: https://some-domain.com/#/getTokens?brand=someBrand&code=572896&lid=7Rewards&optin=Y&env=dev