Abdul Hannan
Abdul Hannan

Reputation: 328

Firebase cloud messaging doesn't show notification when out of window focus

Recently started working on FCM and there are two cases, either you're on browser window you'll get an in app notification within the window using an event listener or if you're off the browser window, you'll get a desktop notification.

In my particular case whenever i'm on window i'm calling an API to fetch data whenever there's a certain message object recieved

navigator.serviceWorker.addEventListener("message", ({ data }) => {
  dispatch(getNotifications(10));
});

this works fine but when I have an open tab but i'm on another window, FCM doesn't get this message object and no event listener is being invoked, essentially I have to either refresh the page or use window.onfocus to re-call the api when I come back to the tab.

Anyone with a workaround?

Upvotes: 2

Views: 1605

Answers (1)

miguelps
miguelps

Reputation: 148

Firebase will not display the message when you are on another tab, sadly.

But you can use the BroadcastChannel API out of the box. It works like a charm. In your service worker you can add this:

const broadcast = new BroadcastChannel('background-message');

messaging.onBackgroundMessage(message => {
    broadcast.postMessage(message);
})

Then in your app listen to 'background-message' channel:

const broadcast = new BroadcastChannel('background-message');
broadcast.onmessage = (event) => {
  console.log('message from service-worker:', event.data)
};

Upvotes: 3

Related Questions