Lesson 24 / 30

Push API

Subscribe users to the Push API, send the subscription to your server and handle push events in the service worker.

Push message delivery

The Push API enables your server to send messages to users via a push service. Messages arrive even when the app is closed, and the service worker handles them.

Subscribe to push messages

Subscribe to push and send endpoint to server.

navigator.serviceWorker.ready.then(reg => {
  reg.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array(PUBLIC_KEY)
  }).then(subscription => {
    console.log('Subscribed:', subscription.endpoint);
    // Send subscription to server
    fetch('/subscribe', {
      method: 'POST',
      body: JSON.stringify(subscription)
    });
  });
});

Output:

App subscribed to push messages; server can now send messages to user.