39 lines
1.4 KiB
JavaScript
39 lines
1.4 KiB
JavaScript
(function initializePwa() {
|
|
function notify(message) {
|
|
window.CognitiveAgentConsole?.notify?.(message);
|
|
}
|
|
|
|
function showUpdate(registration) {
|
|
notify("检测到前端更新,正在刷新页面");
|
|
registration.waiting?.postMessage({ type: "SKIP_WAITING" });
|
|
}
|
|
|
|
async function register() {
|
|
if (!("serviceWorker" in navigator) || !window.isSecureContext) return;
|
|
try {
|
|
const registration = await navigator.serviceWorker.register("/service-worker.js", {
|
|
scope: "/",
|
|
updateViaCache: "none",
|
|
});
|
|
await registration.update();
|
|
if (registration.waiting) showUpdate(registration);
|
|
registration.addEventListener("updatefound", () => {
|
|
const worker = registration.installing;
|
|
worker?.addEventListener("statechange", () => {
|
|
if (worker.state === "installed" && navigator.serviceWorker.controller) {
|
|
showUpdate(registration);
|
|
}
|
|
});
|
|
});
|
|
navigator.serviceWorker.addEventListener("controllerchange", () => window.location.reload());
|
|
navigator.serviceWorker.addEventListener("message", (event) => {
|
|
if (event.data?.type === "OFFLINE_READY") notify("PAD 离线资源已准备完成");
|
|
});
|
|
} catch (error) {
|
|
console.warn("PWA registration failed", error);
|
|
}
|
|
}
|
|
|
|
window.addEventListener("load", register, { once: true });
|
|
})();
|