MDN self-hosted library · e01.org

ServiceWorkerGlobalScope: pushsubscriptionchange event

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
self.addEventListener("pushsubscriptionchange", (event) => {
  const conv = (val) =>
    self.btoa(String.fromCharCode.apply(null, new Uint8Array(val)));
  const getPayload = (subscription) => ({
    endpoint: subscription.endpoint,
    publicKey: conv(subscription.getKey("p256dh")),
    authToken: conv(subscription.getKey("auth")),
  });

  const subscription = self.registration.pushManager
    .subscribe(event.oldSubscription.options)
    .then((subscription) =>
      fetch("register", {
        method: "post",
        headers: {
          "Content-type": "application/json",
        },
        body: JSON.stringify({
          old: getPayload(event.oldSubscription),
          new: getPayload(subscription),
        }),
      }),
    );
  event.waitUntil(subscription);
});
js
self.onpushsubscriptionchange = (event) => {
  event.waitUntil(
    self.registration.pushManager
      .subscribe(event.oldSubscription.options)
      .then((subscription) => {
        /* ... */
      }),
  );
};