Search code examples
safariworkboxworkbox-webpack-plugin

Caching Videos in Safari using Workbox


I have a Vue.js app which i'm currently using workbox to cache so it works offline. However, videos don't seem to work in Safari.

I've researched and all signs point to this: https://developers.google.com/web/tools/workbox/guides/advanced-recipes#cached-av

but it doesn't seem to work for me.

Here's my code as it stands:

Webpack

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

sw.js (service worker)

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);

Solution

  • I realised as I was precaching I had to specify what cache to use in the CacheFirst object, as the default is set to the runtime cache. To do this, I imported cacheNames from workbox-core

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

    Then I set the precache name

    const precacheCacheName = cacheNames.precache;
    

    Then in when setting up the CacheFirst object I specified the name as such:

      new CacheFirst({
        cacheName: precacheCacheName,
    

    Here's the complete code:

    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);