Lesson 23 / 29
Push API
Integrate server push messaging to keep users engaged with timely updates.
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.