代码之家  ›  专栏  ›  技术社区  ›  Ali Sheikhpour

服务工作者无法缓存起始url

  •  0
  • Ali Sheikhpour  · 技术社区  · 4 年前

    我把我的应用程序的PWA版本放在 https://www.example.com/app 文件夹。我尝试过使用以下url格式缓存起始页(在 文件\u到\u缓存 )但都不管用

    "/"
    "/app"
    "/app/"
    "/app/index.php"
    "app"
    "app/index.php"
    "./"
    "./app"
    

    软件js:

    const CACHE_NAME = 'static-cache-v1.2';
    const DATA_CACHE_NAME = 'data-cache';
    
    //Those tries and errors go here one by one
    const FILES_TO_CACHE = [
        "/" 
    ];
    
    self.addEventListener('install', (evt) => {
        console.log('[ServiceWorker] Install');
        evt.waitUntil(
            caches.open(CACHE_NAME).then((cache) => {
                console.log('[ServiceWorker] Pre-caching offline page');
                return cache.addAll(FILES_TO_CACHE);
            }).then(self.skipWaiting())
        );
    
    
    });
    
    self.addEventListener('activate', (evt) => {
        console.log('[ServiceWorker] Activate');
    
        evt.waitUntil(
            caches.keys().then((keyList) => {
                return Promise.all(keyList.map((key) => {
                    if (key !== CACHE_NAME) {
                        console.log('[ServiceWorker] Removing old cache', key);
                        return caches.delete(key);
                    }
                }));
            })
        );
    
        self.clients.claim();
    });
    
    self.addEventListener('fetch', (evt) => {
    console.log('[ServiceWorker] Fetch', evt.request.url);
        evt.respondWith(
    
            caches.open(CACHE_NAME).then(cache => {
                return cache.match(evt.request).then(cacheResponse => cacheResponse || fetch(evt.request).then(networkResponse => {
                    cache.put(evt.request, networkResponse.clone());
                    return networkResponse;
                }));
    
            }))
    });
    

    谷歌chrome灯塔说:

    脱机时start_url不响应200

    <base href="https://www.example.com/app/">
    

    这是我用来注册服务人员的代码 https://www.example.com/app/index.php 并在控制台中接收成功消息:

    <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('sw.js', {scope: '/app/'})
      .then((reg) => {
        console.log("Web workers work");
      }).catch((error) => {
        // registration failed
        console.log('Registration failed with ' + error);
      });
    }  else{
      console.log("No sw available");
      }
    
    </script>
    
    0 回复  |  直到 4 年前