// The page half, as SKILL.md shows it. The buttons start disabled and // are enabled only once they can do something: after the worker is // active and the key is fetched. On a browser without push they stay // disabled, with the reason logged, rather than sitting there inert. import { enable, reconcile, disable, capabilities, status } from "/static/aviso/push.mjs"; const log = (line) => { document.getElementById("log").textContent += line + "\n"; }; const button = (id) => document.getElementById(id); const post = (path) => (body) => fetch(path, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); const save = post("/aviso/subscribe"); const remove = post("/aviso/unsubscribe"); const caps = capabilities(); log("capabilities: " + JSON.stringify(caps)); if (!caps.standalone && /iPhone|iPad/.test(navigator.userAgent)) { document.getElementById("coach").style.display = "block"; } if (!caps.serviceWorker || !caps.push) { log("this browser cannot do push; the buttons stay disabled"); } else { await navigator.serviceWorker.register("/sw.js"); // Active, not merely registered: subscribe() on an installing // worker rejects with InvalidStateError. const registration = await navigator.serviceWorker.ready; const { publicKey } = await (await fetch("/aviso/public-key")).json(); // Every load: repair without prompting, and keep the server's // confirmation moving. const repaired = await reconcile({ registration, publicKey, save }).catch((e) => { log("reconcile: " + e.message); return null; }); log("subscribed: " + !!repaired); // From the click, synchronously: enable prompts before its first await. button("enable").onclick = () => { enable({ registration, publicKey, save }) .then((sub) => log(sub ? "enabled: " + sub.endpoint.slice(0, 40) + "…" : "permission denied")) .catch((e) => log("enable: " + e.message)); }; button("disable").onclick = async () => { try { await disable({ registration, remove }); log("disabled"); } catch (e) { log("disable: " + e.message); } }; button("notify").onclick = async () => { const r = await fetch("/notify", { method: "POST", credentials: "same-origin" }); log("notify: " + r.status + " " + await r.text()); }; for (const id of ["enable", "disable", "notify"]) button(id).disabled = false; const s = await status(registration); log("permission: " + s.permission); }