Skip to content

Instantly share code, notes, and snippets.

@nurmdrafi
Created May 4, 2024 16:33
Show Gist options
  • Save nurmdrafi/b2450322caa2e2b3c034eec342908917 to your computer and use it in GitHub Desktop.
Save nurmdrafi/b2450322caa2e2b3c034eec342908917 to your computer and use it in GitHub Desktop.
Push Notification R&D

// Sending and receiving push messages

  1. if user grant notification permission, the user subscribes to the push service
  2. the push service returns a subscription object, which includes a public key to enable messages to be encrypted and an endpoint URL for the browser's push service, which is unique for each user
  3. send push messages from this URL from server, encrypted with the public key and the push service forward this message to the right client, device and browser
  4. service worker handle the push messages, when a push event is fired shows up message

// subscribe to the push service

navigator.serviceWorker.getRegistration().then(reg => { reg.pushManager .subscribe({ userVisibleOnly: true }) .then(sub => { // send sub.toJSON() to server

	// example
	{
		"endpoint": "https://fcm.googleapis.com...",
		"keys": {
			"p256dh" : "BLadoe2..."
			"auth": "3ldjaf4..."
		}
	}
})

})

// The push event self.addEventListener("push", (event) => { const title = event.data.text(); event.waitUntil(self.registration.showNotification(title)) })

// Push API allows user to subscribe to messages sent from your server via the push service used by the browser

Subscribing is done in the javascript for the page

// Check if user is subscribed navigator.serviceWorker.ready.then(reg => { reg.pushManager.getSubscribtion() .then(sub => { if(sub === undefined){ // ask user to register for push } else { // you have subscription, update the database } }) })

// Send a message from the server const webPush = require('web-push')

function sendMessage(pushSubscription) { const payload = 'here is a payload' const options = { gcmAPIKey: 'your_server_key', TTL: 60 // max time for push service to retry delivery }

webPush.sendNotification(pushSubscription, payload, options)

}

every endpoint need to be unique, otherwise other application be able to send push message to your application.

// Summary A backend service on your server sends a message to a push service using endpoint URL from the subscription object, the message is encrypted with the public key from the subscription.

The push service then uses subscription includes encoded in the endpoint URL to send the message to the right client.

The push event is picked up by the service worker and displays message as a notification.

// Use VAPID to secure push message

  • Voluntary Application Server Identification for Web Push (VAPID) protocol is an optional method to identify your service

Push Notification are not supported in private or incognito mode

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment