带有范围请求插件的Service Worker:离线时无法获取mp3文件 [英] Service worker with range requests plugin: cannot fetch mp3 files when offline
问题描述
我正在处理一个单页PWA,该PWA需要使所有内容都可以脱机使用.
I am working on a single page PWA that needs to have all content available offline.
初始设置和问题:我使用create-react-app设置了基础知识,然后使用react-app-rewired用InjectManifest替换了GenerateSW插件,并在我的服务工作者中对webpack生成的清单进行了一个简单的precacheAndRoute.
Initial setup and problem: I used create-react-app to set up the basics, then used react-app-rewired to replace the GenerateSW plugin with the InjectManifest and do a simple precacheAndRoute of the webpack generated manifest in my service worker.
除了我的mp3文件外,它的工作方式像超级装置一样:在Safari中,我看不到曲目的持续时间,进度条也消失了.在Chrome中或多或少都可以,唯一的问题是播放音频文件时它会切断最后1-2秒的时间.
Worked like a charm, except for my mp3-files: in Safari I could not see the duration of a track and the progress bar was dead. In Chrome it was more or less okay, only problem was that it would cut off the last 1-2 seconds when playing an audio file.
初始解决方案::在我的软件配置中,我为<3- href ="https://developers.google.com/web/tools/workbox/guides/advanced-recipes#cached-av"rel =" nofollow noreferrer> https://developers.google.com/web/tools/workbox/guides/advanced-recipes#cached-av 一个>.一切正常,现在只要我在线,一切都可以在Chrome和Safari中正常运行.当我离线时,可以从缓存中获取除mp3文件以外的所有内容.
Initial solution: In my SW configuration, I added a specific registerRoute for mp3-files that used the range request plugin as per https://developers.google.com/web/tools/workbox/guides/advanced-recipes#cached-av. It sort of worked, now everything works fine in both Chrome and Safari as long as I am online. When I go offline, everything except the mp3-files can be fetched from the cache.
您可以看到她的错误: https://cgl-hunter-kids-test.firebaseapp.com/单击标题图像进入该站点,在左上方菜单中选择历史记录",然后选择9个可用故事中的任何一个.音频播放器在右上角.
You can see the error her: https://cgl-hunter-kids-test.firebaseapp.com/ Click on the title image to enter the site, select "Historien" in the top left menu, and then selected any of the 9 available stories. The audio player is in the top right corner.
在Chrome开发者工具中,我可以看到它在线时会从Service Worker中获取mp3文件.我还可以看到mp3文件确实存在于预缓存中.我不知道为什么离线时找不到它们-有人可以帮忙吗?
In Chrome dev tools, I can see that it fetches the mp3 files from the Service Worker when online. I can also see that the mp3 files do exist in the precache. I have no idea why it cannot find them when offline - can anyone help?
谢谢你,戴安娜(Diana)
Thank you, Diana
我的服务工作者配置:
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 || []);
推荐答案
我知道了!
我必须在我的registerRoute中将matchOptions添加到CacheFirst策略:
I had to add the matchOptions to the CacheFirst strategy in my registerRoute:
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进行托管有关,但我不确定.
It might have been related to using Firebase for hosting, but I am not sure.
这篇关于带有范围请求插件的Service Worker:离线时无法获取mp3文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!