Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
Using a service worker to redirect

I have a use case with my service worker where on certain occasions I need to either reload the page, or redirect the page.

  1. We currently use the service worker as an interceptor for all navigation fetches. Because of this it's important to reload the page when a service worker is activated. I currently do this in the 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.

  1. The second condition is that I need to redirect the user when the url in a service worker's navigation fetch event has a certain query param in it.
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
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda