diff --git a/frontend/plugins/pwaUpdate.client.ts b/frontend/plugins/pwaUpdate.client.ts index 4129f69..ac9ce3c 100644 --- a/frontend/plugins/pwaUpdate.client.ts +++ b/frontend/plugins/pwaUpdate.client.ts @@ -1,50 +1,39 @@ import { Workbox } from "workbox-window"; +import { usePWA } from "~/composables/global/usePwa"; export default defineNuxtPlugin(() => { const updateAvailable = ref(false); let wb: Workbox | null = null; - if ("serviceWorker" in navigator) { + const { isInstalledAsPWA } = usePWA(); + + if ("serviceWorker" in navigator && isInstalledAsPWA.value) { wb = new Workbox("/sw.js"); - const isStandalone = window.matchMedia( - "(display-mode: standalone)" - ).matches; - const isIOSPWA = (window.navigator as any).standalone; - const isInstalledAsPWA = isStandalone || isIOSPWA; - - // Listen for messages from the service worker - navigator.serviceWorker.addEventListener("message", (event) => { - if ( - event.data && - event.data.type === "VERSION_CHECK" - ) { - checkForUpdate(event.data.version); - } + wb.addEventListener("waiting", () => { + checkForUpdate(); }); - // Register the service worker and check if there's already a waiting one - wb.register().then((registration: any) => { - if (registration.waiting) { - checkForUpdate(); - } - }); + wb.register() + .then((registration: any) => { + if (registration.waiting) { + checkForUpdate(); + } + }) + .catch((error) => { + console.error("Service worker registration failed:", error); + }); } - // 🔹 Function to compare versions and show update modal if needed - const checkForUpdate = (newVersion?: string) => { - const currentVersion = localStorage.getItem("pwa_version"); - - if (newVersion && currentVersion !== newVersion) { - updateAvailable.value = true; - localStorage.setItem("pwa_version", newVersion); - } + const checkForUpdate = () => { + updateAvailable.value = true; }; - - // 🔹 Function to apply the update const handleUpdate = () => { - wb?.messageSW({ type: "SKIP_WAITING" }); - window.location.reload(); + if (wb) { + wb.messageSW({ type: "SKIP_WAITING" }).then(() => { + window.location.reload(); + }); + } }; return {