Example 1 — Check Subscription & Update UI
MDN pattern after serviceWorker.ready.
navigator.serviceWorker.ready.then((registration) => {
registration.pushManager
.getSubscription()
.then((subscription) => {
const pushButton = document.querySelector(".js-push-button");
pushButton.disabled = false;
if (!subscription) {
// Not subscribed — keep Enable UI
return;
}
// Keep server in sync + show Disable UI
sendSubscriptionToServer(subscription);
pushButton.textContent = "Disable Push Messages";
})
.catch((err) => {
console.error(`Error during getSubscription(): ${err}`);
});
}); How It Works
- Wait for ready. You need a live service worker registration.
- Call getSubscription. No parameters; returns a Promise.
- Branch on null. First-time users usually have no subscription.
- Restore UI. If subscribed, sync to the server and flip the button text.

