簡體   English   中英

服務工作者緩存破壞谷歌地圖 api

[英]service worker cacheing breaking google maps api

我無法讓我的漸進式 web 應用程序運行。 我需要阻止它緩存谷歌地圖 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 並從服務器獲取如果它是谷歌 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/'))
        );
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM