Files
hossein-por-shop/frontend/plugins/pwaUpdate.client.ts
T
2025-03-18 20:35:58 +03:30

46 lines
1.1 KiB
TypeScript

import { Workbox } from "workbox-window";
import { usePWA } from "~/composables/global/usePwa";
export default defineNuxtPlugin(() => {
const updateAvailable = ref(false);
let wb: Workbox | null = null;
const { isInstalledAsPWA } = usePWA();
if ("serviceWorker" in navigator && isInstalledAsPWA.value) {
wb = new Workbox("/sw.js");
wb.addEventListener("waiting", () => {
checkForUpdate();
});
wb.register()
.then((registration: any) => {
if (registration.waiting) {
checkForUpdate();
}
})
.catch((error) => {
console.error("Service worker registration failed:", error);
});
}
const checkForUpdate = () => {
updateAvailable.value = true;
};
const handleUpdate = () => {
if (wb) {
wb.messageSW({ type: "SKIP_WAITING" }).then(() => {
window.location.reload();
});
}
};
return {
provide: {
updateAvailable,
handleUpdate,
},
};
});