import { Workbox } from "workbox-window"; export default defineNuxtPlugin(() => { const updateAvailable = ref(false); let wb: Workbox | null = null; // Enhanced PWA detection const isStandalone = window.matchMedia( "(display-mode: standalone)" ).matches; const isIOSPWA = (window.navigator as any).standalone; const isInstalledAsPWA = isStandalone || isIOSPWA; if ("serviceWorker" in navigator && isInstalledAsPWA) { wb = new Workbox("/sw.js"); // Listen for version checks from SW wb.addEventListener("message", (event) => { if (event.data.type === "VERSION_CHECK") { checkForUpdate(event.data.version); } }); // Register service worker wb.register().then((registration: any) => { if (registration.waiting) { checkForUpdate(); } }); // Detect controller changes for updates wb.addEventListener("controlling", () => { window.location.reload(); }); } const checkForUpdate = (newVersion?: string) => { const currentVersion = localStorage.getItem("pwa_version"); if (!newVersion) { // If no version provided, just trigger update updateAvailable.value = true; return; } if (currentVersion !== newVersion) { updateAvailable.value = true; localStorage.setItem("pwa_version", newVersion); } }; const handleUpdate = () => { if (!!wb) { wb.messageSW({ type: "SKIP_WAITING" }); } }; return { provide: { updateAvailable, handleUpdate, }, }; });