【问题标题】:Service worker with range requests plugin: cannot fetch mp3 files when offline具有范围请求插件的服务工作者:离线时无法获取 mp3 文件
【发布时间】:2020-05-26 12:55:03
【问题描述】:

我正在开发一个需要离线提供所有内容的单页 PWA。

初始设置和问题: 我使用 create-react-app 来设置基础,然后使用 react-app-rewired 将 GenerateSW 插件替换为 InjectManifest 并在我的 service worker 中对 webpack 生成的清单进行简单的 precacheAndRoute。

工作就像一个魅力,除了我的 mp3 文件:在 Safari 中,我看不到曲目的持续时间,进度条已经死了。在 Chrome 中它或多或少没问题,唯一的问题是它会在播放音频文件时切断最后 1-2 秒。

初始解决方案:在我的 SW 配置中,我为使用范围请求插件的 mp3 文件添加了一个特定的 registerRoute,根据 https://developers.google.com/web/tools/workbox/guides/advanced-recipes#cached-av。它有点工作,现在只要我在线,Chrome 和 Safari 都可以正常工作。当我离线时,除了 mp3 文件之外的所有内容都可以从缓存中获取。

你可以看到她的错误:https://cgl-hunter-kids-test.firebaseapp.com/ 点击标题图片进入网站,在左上角菜单中选择“Historien”,然后选择 9 个可用故事中的任何一个。音频播放器位于右上角。

在 Chrome 开发工具中,我可以看到它在线时从 Service Worker 获取 mp3 文件。我还可以看到 mp3 文件确实存在于预缓存中。我不知道为什么离线时找不到它们 - 任何人都可以帮忙吗?

谢谢你, 戴安娜

我的 service worker 配置:

const COOKIE_CONSENT_ENDPOINT = '/hunterkidsCookieConsent';
const GAME_DATA_ENDPOINT      = '/hunterkidsGameData';

/* Use client claim to handle SW updates */
workbox.core.clientsClaim();

/* Activate new SW (user triggered) */
self.addEventListener('message', (event) => {
    if (event.data.action === 'skipWaiting') self.skipWaiting();
});

/* Cache files from _precacheManifest (generated by InjectManifest webpack plugin) */
self.__precacheManifest = [].concat(self.__precacheManifest || []);

self.addEventListener('activate', (event) => {event.waitUntil(clients.claim());});

/* Handle ranged quests of mp3 files */
// https://github.com/GoogleChrome/workbox/issues/1644
// https://developers.google.com/web/tools/workbox/guides/advanced-recipes#cached-av
workbox.routing.registerRoute(
  ({url}) => url.pathname.endsWith('.mp3'),
  new workbox.strategies.CacheFirst({
    cacheName: workbox.core.cacheNames.precache,
    plugins: [     
        new workbox.cacheableResponse.Plugin({ statuses: [200] }),
        new workbox.rangeRequests.Plugin(),
      ],
  })
);

/* Special fetch requests */
self.addEventListener('fetch', function(event) {
    const {
        request,
        request: {url, method},
  } = event;
  /* Game progress */
  if (url.match(GAME_DATA_ENDPOINT)) {
    if (method === 'POST') {
      /* Write data to cache */
      request.json().then(body => {
        caches.open(GAME_DATA_ENDPOINT).then(function(cache) {
          cache.put(GAME_DATA_ENDPOINT, new Response(JSON.stringify(body)));
        });
      }); 
      return new Response('{}');
    } else {
      /* Read data from cache */
      event.respondWith(
        caches.open(GAME_DATA_ENDPOINT).then(function(cache) {
          return cache.match(GAME_DATA_ENDPOINT).then(function (response) {
            return response || new Response('{}');;
          }) || new Response('{}');
          })
      );
    }
  }

  /* Cookie consent */ 
  if (url.match(COOKIE_CONSENT_ENDPOINT)) {
    if (method === 'POST') {
      /* Write data to cookie */
      request.json().then(body => {
        caches.open(COOKIE_CONSENT_ENDPOINT).then(function(cache) {
          cache.put(COOKIE_CONSENT_ENDPOINT, new Response(JSON.stringify(body)));
        });
      }); 
      return new Response('{}');
    } else {
      /* Read data from cookie */
      event.respondWith(
        caches.open(COOKIE_CONSENT_ENDPOINT).then(function(cache) {
          return cache.match(COOKIE_CONSENT_ENDPOINT).then(function (response) {
            return response || new Response('{}');;
          }) || new Response('{}');
        })
      );
    }
  }
});

/* All other requests */
workbox.precaching.precacheAndRoute(self.__precacheManifest || []);

【问题讨论】:

    标签: caching audio service-worker firebase-hosting workbox


    【解决方案1】:

    我想通了!

    我必须在我的 registerRoute 中将 matchOptions 添加到 CacheFirst 策略:

    workbox.routing.registerRoute(
      ({url}) => url.pathname.endsWith('.mp3'),
      new workbox.strategies.CacheFirst({
        cacheName: workbox.core.cacheNames.precache,
        plugins: [     
            new workbox.cacheableResponse.Plugin({ statuses: [200] }),
            new workbox.rangeRequests.Plugin(),
          ],
        matchOptions: {
          ignoreSearch: true,
          ignoreVary: true
        }
      })
    );
    

    这可能与使用 Firebase 进行托管有关,但我不确定。

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 2017-01-31
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      相关资源
      最近更新 更多