服务工作者缓存中断 google 映射 api

service worker cacheing breaking google maps api

我无法让我的渐进式网络应用程序正常工作。我需要阻止它缓存 google 映射 api。我试图让它不会在域外缓存任何东西,但似乎无法弄清楚。

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/'))
  );
});

我添加了以下语句以试图阻止它缓存本地域之外的任何内容,但我做错了,它只是抛出获取错误。

if ((evt.request.url).includes(window.location.host)) {

您应该检查 url 并从服务器获取如果它是 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/'))
        );
    }
});

@nechoj 截取的代码完美运行。只是对其进行了一些修改,以仅缓存同一域中的资产。

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/'))
        );
    }
});