This commit is contained in:
Mamalizz
2025-03-06 23:06:56 +03:30
parent 68c355087c
commit 88a020bcaf
2 changed files with 18 additions and 46 deletions
+10 -27
View File
@@ -4,55 +4,38 @@ 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) {
if ("serviceWorker" in navigator) {
wb = new Workbox("/sw.js");
// Listen for version checks from SW
wb.addEventListener("message", (event) => {
if (event.data.type === "VERSION_CHECK") {
// 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 service worker
// Register the service worker and check if there's already a waiting one
wb.register().then((registration: any) => {
if (registration.waiting) {
checkForUpdate();
}
});
// Detect controller changes for updates
wb.addEventListener("controlling", () => {
window.location.reload();
});
}
// 🔹 Function to compare versions and show update modal if needed
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) {
if (newVersion && currentVersion !== newVersion) {
updateAvailable.value = true;
localStorage.setItem("pwa_version", newVersion);
}
};
// 🔹 Function to apply the update
const handleUpdate = () => {
if (!!wb) {
wb.messageSW({ type: "SKIP_WAITING" });
}
wb?.messageSW({ type: "SKIP_WAITING" });
window.location.reload();
};
return {