@vue/cli-plugin-pwa not serving content offline after using Workbox injectManifest

82 Views Asked by At

I've updated @vue/cli-plugin-pwa from v3 to v5 and used the injectManifest option. The app works as expected, but when I go offline and refresh the page, it goes blank and no longer loads. However, if I navigate within the app while offline without refreshing the page, it works just fine.

Here's the code for my service worker (service-worker.js):

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

import {
  createHandlerBoundToURL,
  precacheAndRoute,
  cleanupOutdatedCaches,
} from "workbox-precaching";
import { NavigationRoute, registerRoute } from "workbox-routing";
import { clientsClaim } from "workbox-core";
import { StaleWhileRevalidate } from "workbox-strategies";

self.skipWaiting()
clientsClaim()

// Use with precache injection
precacheAndRoute(self.__WB_MANIFEST)
cleanupOutdatedCaches()
registerRoute(new NavigationRoute(createHandlerBoundToURL("/index.html")));


const bgSyncQueue = new workbox.backgroundSync.Queue("uploadQueue", {
  maxRetentionTime: 60 * 24 * 60,
  onSync: () => syncData(),
});

self.onfetch = (event) => {
  let requestClone = event.request.clone();
  const methodsToReply = ["POST", "PUT", "DELETE"];
  if (
    methodsToReply.includes(requestClone.method) &&
    requestClone.url.includes("firststep.zinpro.cn/api/")
  ) {
    event.respondWith(
      (() => {
        const promiseChain = fetch(requestClone).catch(() => {
          return bgSyncQueue.pushRequest(event);
        });
        event.waitUntil(promiseChain);
        return promiseChain;
      })()
    );
  } else {
    caches.match(event.request) || event.respondWith(fetch(event.request));
  }
};

async function syncData() {
  let entry;
  while ((entry = await bgSyncQueue.shiftRequest())) {
    try {
      console.log("sync data running", entry);
      let clone = entry.request.clone();
      let response = await fetch(clone);
      console.error("Replay successful for request", entry.request);
    } catch (error) {
      console.error("Replay failed for request", entry.request, error);
      // Put the entry back in the bgSyncQueue and re-throw the error:
      await bgSyncQueue.unshiftRequest(entry);
      throw error;
    }
  }
  console.log("Replay complete!");
}

self.addEventListener("message", function (event) {
  console.log(
    "onMessage function running, event.data.text === sync",
    event.data
  );
  if (event.data.text === "sync") {
    try {
      event.waitUntil(syncData());
    } catch (error) {
      // event.waitUntil(syncData())
    }
  }
});

Here is the code of vue pwa config

const { defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
  pwa: {
    name: "Zinpro First Step",
    short_name: "Zinpro",
    themeColor: "#000000",
    workboxPluginMode: "InjectManifest",
    workboxOptions: {
      swSrc: "./src/service-worker.js", // CHECK CORRECT PATH!
    },
    themeColor: "#000000",

    iconPaths: {
      favicon32: "icons/ZinproFavicon32x32.png",
      favicon16: "icons/ZinproFavicon32x32.png",
      appleTouchIcon: "icons/Zinpro_App_Icon_192x192.png",
      maskIcon: "icons/safari-pinned-tab.svg",
      msTileImage: "icons/Zinpro_App_Icon_192x192.png",
    },
  },
});

The website needs to be cached to serve offline, and the URL is

https://devsgp.firststep.zinpro.cn/.

I've been trying to figure this out for a few days now but haven't had any luck. Can anyone please help me solve this issue?

0

There are 0 best solutions below