Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda