Skip to content

Commit

Permalink
Merge pull request #53 from signalwire/joao/background_push_notificat…
Browse files Browse the repository at this point in the history
…ions

Send push from the background message
  • Loading branch information
jpsantosbh authored Feb 20, 2024
2 parents 3e981b9 + b4604d8 commit 96577a7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
13 changes: 10 additions & 3 deletions public/full.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,20 @@ async function enablePushNotifications() {
const messaging = FB.getMessaging(app)

FB.onMessage(messaging, (payload) => {
console.log('Push payload', payload)
const body = JSON.parse(payload.notification.body || '{}')
handlePushNotification(body)
console.log('Push payload.data.message', payload.data.message)
const message = JSON.parse(payload.data.message);
handlePushNotification(message.notification.body)
alert(body.title)
})

try {
navigator.serviceWorker.addEventListener('message', event => {
console.log(`The service worker sent me a message: ${event.data}`);
const message = JSON.parse(event.data || '{}')
handlePushNotification(message.notification.body)
alert(body.title)
});

const registration = await navigator.serviceWorker.register(
'/service-worker.js',
{
Expand Down
14 changes: 12 additions & 2 deletions views/service-worker.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@ try {
const firebaseApp = firebase.initializeApp(config)

// Retrieve an instance of Firebase Messaging so that it can handle background messages.
firebase.messaging().onBackgroundMessage((payload) => {
firebase.messaging().onBackgroundMessage((message) => {
console.log(
'[service-worker.js] Received background message ',
payload
message
)

const payload = JSON.parse(message.data.message);

// Customize notification here
const notificationTitle = payload.notification.body?.title
const notificationOptions = {
Expand All @@ -31,6 +34,13 @@ try {

console.log('Notification', payload.notification)

self.clients.matchAll().then(function(clients) {
clients.forEach(function(client) {
console.log(client);
client.postMessage(message.data.message);
});
});

self.registration.showNotification(notificationTitle, notificationOptions)
})
} catch (error) {
Expand Down

0 comments on commit 96577a7

Please sign in to comment.