简体   繁体   中英

How to trigger an event at App.tsx from onBackgroundMessage in firebase-messaging-sw.js with react

I have a file firebase-messaging-sw.js in the public folder. When the app server sends a message and the browser is in the background, the onBackgroundMessage function is fired and shows a notification. here is the code:

const messaging = firebase.messaging();
messaging.onBackgroundMessage(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = payload.notification?.title;
  const notificationOptions = {
    body: payload.notification?.body,
    icon: '/firebase-logo.png'
  };
  
  self.registration.showNotification(notificationTitle, notificationOptions);
  // Call a function in app.tsx to show a modal dialog when the user back to the browser
  //code example
});

I want when onBackgroundMessage is fired then it will fire a function at app.tsx of react. How do you do that?

self.client.postMessage are helping to triggering the event
initMessaging.onBackgroundMessage(function(payload) {
  console.log('Received background message ', payload);
  
 // Customize notification here
  const notification = payload.data;
  const notificationTitle = payload.data.body.title;
  const notificationOptions = {
    body: payload.data.body,
  };
  **self.clients.matchAll({
    type: 'window',
    includeUncontrolled: true
  }).then(all => all.forEach(client => {
    console.log('client',client)
    client.postMessage(payload);
    // client.postMessage("Responding to ");
   }))**
   self.registration.showNotification(notificationTitle,
    notificationOptions);
});

How do you handle postmessage event in app.tsx. I can not receive event postmessage from onBackgroundMessage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM