使用 Workbox 在 Safari 中缓存视频

Caching Videos in Safari using Workbox

我有一个 Vue.js 应用程序,我目前正在使用 workbox 进行缓存,因此它可以离线工作。但是,视频似乎无法在 Safari 中播放。

我研究过,所有迹象都表明: https://developers.google.com/web/tools/workbox/guides/advanced-recipes#cached-av

但它似乎对我不起作用。

这是我的代码:

Webpack

configureWebpack: {
plugins: [
  new InjectManifest({
    swSrc: './src/sw.js',
    swDest: "sw.js",
    maximumFileSizeToCacheInBytes: 5000000000
  })
]}

sw.js(服务人员)

import { skipWaiting, clientsClaim } from "workbox-core";
import { precacheAndRoute } from "workbox-precaching";
import { registerRoute } from "workbox-routing";
import { CacheFirst } from "workbox-strategies";
import { CacheableResponsePlugin } from "workbox-cacheable-response";
import { RangeRequestsPlugin } from "workbox-range-requests";

registerRoute(
  ({ url }) => url.pathname.endsWith(".mp4"),
  new CacheFirst({
    plugins: [
      new CacheableResponsePlugin({ statuses: [200] }),
      new RangeRequestsPlugin()
    ]
  })
);

skipWaiting();
clientsClaim();
precacheAndRoute(self.__WB_MANIFEST);

这可能是因为您的 .mp4 文件在缓存中附加了 __WB_MANIFEST URL 查询参数,因为它们需要由 Workbox 的预缓存逻辑进行版本控制。

一个快速的解决方案是在构建策略时设置 matchOptions

new CacheFirst({
  matchOptions: { ignoreSearch: true },
  plugins: [
    new CacheableResponsePlugin({ statuses: [200] }),
    new RangeRequestsPlugin()
  ]
})

我意识到在进行预缓存时我必须指定要在 CacheFirst 对象中使用的缓存,因为默认设置为运行时缓存。为此,我从 workbox-core

导入了 cacheNames
import { skipWaiting, clientsClaim, cacheNames } from "workbox-core";

然后我设置预缓存名称

const precacheCacheName = cacheNames.precache;

然后在设置 CacheFirst 对象时,我指定了这样的名称:

  new CacheFirst({
    cacheName: precacheCacheName,

完整代码如下:

import { skipWaiting, clientsClaim, cacheNames } from "workbox-core";
import { precacheAndRoute } from "workbox-precaching";
import { registerRoute } from "workbox-routing";
import { CacheFirst } from "workbox-strategies";
import { CacheableResponsePlugin } from "workbox-cacheable-response";
import { RangeRequestsPlugin } from "workbox-range-requests";

const precacheCacheName = cacheNames.precache;

registerRoute(
  ({ url }) => url.pathname.endsWith(".mp4"),
  new CacheFirst({
    cacheName: precacheCacheName,
    matchOptions: { ignoreSearch: true },
    plugins: [
      new CacheableResponsePlugin({ statuses: [200] }),
      new RangeRequestsPlugin()
    ]
  })
);

skipWaiting();
clientsClaim();
precacheAndRoute(self.__WB_MANIFEST);