added pwa standalone
This commit is contained in:
@@ -1,50 +1,39 @@
|
|||||||
import { Workbox } from "workbox-window";
|
import { Workbox } from "workbox-window";
|
||||||
|
import { usePWA } from "~/composables/global/usePwa";
|
||||||
|
|
||||||
export default defineNuxtPlugin(() => {
|
export default defineNuxtPlugin(() => {
|
||||||
const updateAvailable = ref(false);
|
const updateAvailable = ref(false);
|
||||||
let wb: Workbox | null = null;
|
let wb: Workbox | null = null;
|
||||||
|
|
||||||
if ("serviceWorker" in navigator) {
|
const { isInstalledAsPWA } = usePWA();
|
||||||
|
|
||||||
|
if ("serviceWorker" in navigator && isInstalledAsPWA.value) {
|
||||||
wb = new Workbox("/sw.js");
|
wb = new Workbox("/sw.js");
|
||||||
|
|
||||||
const isStandalone = window.matchMedia(
|
wb.addEventListener("waiting", () => {
|
||||||
"(display-mode: standalone)"
|
checkForUpdate();
|
||||||
).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()
|
||||||
wb.register().then((registration: any) => {
|
.then((registration: any) => {
|
||||||
if (registration.waiting) {
|
if (registration.waiting) {
|
||||||
checkForUpdate();
|
checkForUpdate();
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error("Service worker registration failed:", error);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🔹 Function to compare versions and show update modal if needed
|
const checkForUpdate = () => {
|
||||||
const checkForUpdate = (newVersion?: string) => {
|
updateAvailable.value = true;
|
||||||
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 = () => {
|
const handleUpdate = () => {
|
||||||
wb?.messageSW({ type: "SKIP_WAITING" });
|
if (wb) {
|
||||||
window.location.reload();
|
wb.messageSW({ type: "SKIP_WAITING" }).then(() => {
|
||||||
|
window.location.reload();
|
||||||
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
Reference in New Issue
Block a user