48 lines
1.4 KiB
TypeScript
48 lines
1.4 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");
|
|
|
|
// 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,
|
|
},
|
|
};
|
|
});
|