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

262
Visualizações
service worker cacheing breaking google maps api

Im having trouble getting my progressive web app to work. I need to prevent it from caching the google maps api. I've tried to make it so it won't cache anything outside the domain but cant seem to figure it out.

cacheId = cacheIdRelace;
staticCache = "static-" + cacheId;
dynamicCache = "dynamic-" + cacheId;

self.addEventListener('install', function(event) {
  console.log('[Service Worker] Installing Service Worker ...', event);
  self.skipWaiting();
  event.waitUntil(
    caches.open(staticCache).then(function(cache) {
      cache.addAll(['/', '/index.html','offline/index.html', '/manifest.json', '/style/main.css']);
    })
  );
});

self.addEventListener('activate', evt => {
  console.log('[Service Worker] Activating Service Worker ....');
  evt.waitUntil(
    caches.keys().then (keys =>{
      //console.log(keys);
      return Promise.all(keys
        .filter(key => key !== staticCache && key !== dynamicCache)
        .map(key => caches.delete(key))
      )
    })
  )
});

self.addEventListener('fetch', evt => {
  evt.respondWith(
    caches.match(evt.request).then(cacheRes => {
      return cacheRes || fetch(evt.request).then(fetchRes => {
        return caches.open(dynamicCache).then(cache => {
          if ((evt.request.url).includes(window.location.host)) {
            cache.put(evt.request.url, fetchRes.clone());
          }
          fetchRes.clone()
          return fetchRes
        })
      });
    }).catch(() => caches.match('/offline/'))
  );
});

I added the following statement in to try to prevent it from caching anything outsite the local domain but I've done something wrong and it just throws fetch errors.

if ((evt.request.url).includes(window.location.host)) {
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You should check for the url and fetch from server if it is the google api:

self.addEventListener('fetch', function (event) {
    // no caching google api
    if (event.request.url.indexOf('maps.googleapis.com/maps/api/') > -1) {
        event.respondWith(
            fetch(event.request).then(
                function (response) {
                    // Check if we received a valid response
                    if (!response) {
                        console.error("fetch eventhandler error: no response");
                        return Response.error();
                    }
                    if (!response.ok) {
                        console.warn("fetch eventhandler warning: status=", response.status, response.type);
                        return response;
                    }
                    // ok
                    return response;
                }).catch(function () {
                  // failed access
                  console.error("fetch eventhandler error");
                  return Response.error();
            }))
    } else {
        event.respondWith(
            caches.match(event.request).then(cacheRes => {
                return cacheRes || fetch(event.request).then(fetchRes => {
                    return caches.open(dynamicCache).then(cache => {
                        if ((event.request.url).includes(window.location.host)) {
                            cache.put(event.request.url, fetchRes.clone());
                        }
                        fetchRes.clone()
                        return fetchRes
                    })
                });
            }).catch(() => caches.match('/offline/'))
        );
    }
});
about 4 years ago · Juan Pablo Isaza Relatório

0

@nechoj code sniped works perfectly. Just modified it a bit to only cache assets that are on the same domain.

self.addEventListener('fetch', function (event) {
    // no caching google api
    if (!(event.request.url.indexOf(self.location.host) > -1)) {
        event.respondWith(
            fetch(event.request).then(
                function (response) {
                    // Check if we received a valid response
                    if (!response) {
                        console.error("fetch eventhandler error: no response");
                        return Response.error();
                    }
                    if (!response.ok) {
                        console.warn("fetch eventhandler warning: status=", response.status, response.type);
                        return response;
                    }
                    // ok
                    return response;
                }).catch(function () {
                  // failed access
                  console.error("fetch eventhandler error");
                  return Response.error();
            }))
    } else {
        event.respondWith(
            caches.match(event.request).then(cacheRes => {
                return cacheRes || fetch(event.request).then(fetchRes => {
                    return caches.open(dynamicCache).then(cache => {
                        cache.put(event.request.url, fetchRes.clone());
                        return fetchRes
                    })
                });
            }).catch(() => caches.match('/offline/'))
        );
    }
});
about 4 years ago · Juan Pablo Isaza Relatório
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