Service Worker 未获取缓存文件

问题描述

当我尝试访问 http://localhost/visites/ 时,它应该获取预缓存文件 visites/index.PHP 。所以我想我必须在某个地方指出这个特定的路由匹配那个文件,你知道我该怎么做吗?

我把我的软件代码在这里以防万一:

const cacheName = 'v1';

const cacheAssets = [
    'accueil.PHP','js/accueil.js','visites/index.PHP','js/visites.js','js/global.js','css/styles.css','charte/PICTOS/BTN-Visites.png','charte/STRUCTURE/GESTEL-logo.png','charte/PICTOS/BTN-Animaux.png','charte/PICTOS/BTN-Deconnexion.png','charte/PICTOS/BTN-Fermes.png',];

// Call Install Event
self.addEventListener('install',e => {
  console.log('Service Worker: Installed');

  e.waitUntil(
    caches
      .open(cacheName)
      .then(cache => {
        console.log('Service Worker: Caching Files');
        cache.addAll(cacheAssets);
      })
      .then(() => self.skipwaiting())
  );
});

// Call Activate Event
self.addEventListener('activate',e => {
  console.log('Service Worker: Activated');
  // Remove unwanted caches
  e.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cache => {
          if (cache !== cacheName) {
            console.log('Service Worker: Clearing Old Cache');
            return caches.delete(cache);
          }
        })
      );
    })
  );
});

// Call Fetch Event
self.addEventListener('fetch',e => {
  console.log('Service Worker: Fetching');
  e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
})

解决方法

您可以在 fetch 处理程序中包含一些处理此路由信息的逻辑:

self.addEventListener('fetch',e => {
  // Use a URL object to simplify checking the path.
  const url = new URL(e.request.url);

  // Alternatively,check e.request.mode === 'navigate' if
  // you want to match a navigation to any URL on your site.
  if (url.pathname === '/visites/') {
    e.respondWith(caches.match('visites/index.php'));
    // Return after responding,so that the existing
    // logic doesn't get triggered.
    return;
  }

  e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
});

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...