Files
hossein-por-shop/frontend/plugins/pwaUpdate.client.ts
T
2025-03-07 01:05:05 +03:30

57 lines
1.6 KiB
TypeScript

import { Workbox } from "workbox-window";
export default defineNuxtPlugin(() => {
const updateAvailable = ref(false);
let wb: Workbox | null = null;
if ("serviceWorker" in navigator) {
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);
}
});
// Register the service worker and check if there's already a waiting one
wb.register().then((registration: any) => {
if (registration.waiting) {
checkForUpdate();
}
});
}
// 🔹 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);
}
};
// 🔹 Function to apply the update
const handleUpdate = () => {
wb?.messageSW({ type: "SKIP_WAITING" });
window.location.reload();
};
return {
provide: {
updateAvailable,
handleUpdate,
},
};
});