Страница Google Workbox Offline, чтобы заменить страницу динозавра на очень простой сайт - PullRequest
0 голосов
/ 10 января 2019

У меня очень простой тестовый сайт с 6 страницами: temp1.html, temp2.html, temp3.html, temp4.html, temp11.html страниц и оффлайн.html. Все ссылки на страницы жестко закодированы. Там нет маршрутизации. Я предварительно кэширую все файлы, кроме temp11.html.

Я хочу, чтобы offline.html отображался, когда выбран файл temp11.html и сеть не подключена. Я получаю обычный Chrome-динозавр, когда сеть не подключена, и захожу на temp11.html. Другие проповедованные страницы обслуживаются в автономном режиме, как и ожидалось.

Любые предложения приветствуются.

sw.js

-------------------
/* Welcome to your Workbox-powered service worker! */

importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.0.0-beta.0/workbox-sw.js");

/*

 * The workboxSW.precacheAndRoute() method efficiently caches and responds to

 * requests for URLs in the manifest.

 */

self.__precacheManifest = [
  {
    "url": "offline.html",
    "revision": "0e4b2f63e24f0e31badb470bf5812104"
  },
  {
    "url": "temp1.html",
    "revision": "be08f4cb03aa40aaf0bafbaa620efa48"
  },

  {
    "url": "temp2.html",
    "revision": "91fa624804aaaa7209545ca718b76230"
  },

  {
    "url": "temp3.html",
    "revision": "4e8753d5fc6ab011b813cac6e9a82e7b"
  },

  {
    "url": "temp4.html",
    "revision": "3f09411bc88c33dab4413aa3d467c20e"
  }

].concat(self.__precacheManifest || []);

workbox.precaching.suppressWarnings();

workbox.precaching.precacheAndRoute(self.__precacheManifest, {});


// Use a stale-while-revalidate strategy for all other requests.
//workbox.routing.setDefaultHandler(
//  workbox.strategies.staleWhileRevalidate()
//);

// This "catch" handler is triggered when any of the other routes fail to
// generate a response.
workbox.routing.setCatchHandler(({event}) => {

  // Use event, request, and url to figure out how to respond.

  // One approach would be to use request.destination, see

  // https://medium.com/dev-channel/service-worker-caching-strategies-based-on-request-types-57411dd7652c

  switch (event.request.destination) {

default:
      // If we don't have a fallback, just return an error response.

      return Response.error();
  }
});

1 Ответ

0 голосов
/ 11 января 2019

Изменяя нижнюю часть sw.js, она теперь работает.

В автономном режиме Html-коды состояния 200 генерируются, когда я ввожу URL-адрес .html, которого нет в кэше для этого веб-сайта, например. test101.html. Затем он вызывает offline.html.

Это также ведет себя так же, когда в сети. Я предполагаю, что это правильное поведение.

/**
 * Welcome to your Workbox-powered service worker!
 *
 * You'll need to register this file in your web app and you should
 * disable HTTP caching for this file too.

 *
 * The rest of the code is auto-generated. Please don't update this file
 * directly; instead, make changes to your Workbox build configuration
 * and re-run your build process.

 */


importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.0.0-beta.0/workbox-sw.js");

/**
 * The workboxSW.precacheAndRoute() method efficiently caches and responds to
 * requests for URLs in the manifest.
 */
self.__precacheManifest = [
  {
    "url": "offline.html",
    "revision": "0e4b2f63e24f0e31badb470bf5812104"
  },
  {
    "url": "temp1.html",
    "revision": "be08f4cb03aa40aaf0bafbaa620efa48"
  },
  {
    "url": "temp2.html",
    "revision": "91fa624804aaaa7209545ca718b76230"
  },
  {
    "url": "temp3.html",
    "revision": "4e8753d5fc6ab011b813cac6e9a82e7b"
  },
  {
    "url": "temp4.html",
    "revision": "3f09411bc88c33dab4413aa3d467c20e"
  }
].concat(self.__precacheManifest || []);

workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
//    
//new bottom section     
//
    workbox.routing.registerRoute(
      new RegExp('/*.html'),
      async ({event}) => {
        try {
          return await workbox.strategies.networkFirst().handle({event});
        } catch (error) {
          return caches.match('/offline.html');
        }
      }
    );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...