Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data to angular app from setBackgroundMessageHandler() when using Firebase in Javascript?

I am using firebase in my angular app to send push notification in web.I implemented messaging.onMessage() for receiving notification when app is in foreground and messaging.setBackgroundMessageHandler() when app is in background.I receive notification without any problem but i need to update values based on the notification is received.I could do update when using messaging.onMessage() but how could we do that when using messaging.setBackgroundMessageHandler(). Even it will be ok if i can store the received value locally and get it in my app.

I did research on this is many places but i couldn't find any solution. Can some one help me with this? Thanks!

importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js');

var config = {
    apiKey: "MY_API_KEY",
    authDomain: "MY_AUTH_DOMAIN",
    databaseURL: "MY_DB_URL",
    storageBucket: "URL",
    messagingSenderId: "VALID_ID"
};

firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
return self.registration.showNotification("Title", {body: 'New notification.',})   
});
like image 343
Sharath Avatar asked Nov 08 '22 21:11

Sharath


1 Answers

After searching for days found a Github page that contains a solution for it.

What you can do is get a list of window clients which will return a list of the tabs for your origin and then post a message to each window client. (This code would be in the setBackgroundMessageHandler()).

To get list of pages is:

const promiseChain = clients.matchAll({
type: 'window',
includeUncontrolled: true
})
.then((windowClients) => {
for (let i = 0; i < windowClients.length; i++) {
  const windowClient = windowClients[i];
  windowClient.postMessage(data);
}
})
.then(() => {
return registration.showNotification('my notification title');
});
return promiseChain;

Then to receive the message in the page, add a listener like so:

navigator.serviceWorker.addEventListener('message', function(event) {
console.log('Received a message from service worker: ', event.data);
});

Thanks alot guys who contributed in Github. For more reference go to

https://web-push-book.firebaseapp.com/chapter-05/04-common-notification-patterns/#message-page-from-a-push-event

Hope it will be helpful for you guys.Ping or comment me if you get any doubts in implementing.

like image 106
Sharath Avatar answered Nov 15 '22 06:11

Sharath