quickstart-js icon indicating copy to clipboard operation
quickstart-js copied to clipboard

setBackgroundMessageHandler not called when browser isn't active application

Open jemise111 opened this issue 9 years ago • 5 comments

Hey guys, this is an awesome example repo and I've been able to achieve most of what I'm looking for with a few tweaks. One thing I'm still confused about is:

If I'm actively looking at Chrome but I'm not focused on my web app's tab then I receive my notification in the setBackgroundMessageHandler as expected. However..

If my active tab in Chrome is my web app's tab yet I change applications entirely from Chrome to, say, Spotify (where Spotify now takes over my whole screen, hiding the Chrome window) the setBackgroundMessageHandler is never called at the onMessage handler is called.

Is there anything I can do to change this behavior? It's preventing me from showing notifications even though my web app is hidden.

(FWIW I'm on a mac and my notification payload does NOT include the notification property)

Thanks for any help!

jemise111 avatar Apr 10 '17 20:04 jemise111

You could also show a notification from your page:

navigator.getRegistrations().then((regs) => {
    regs[0].showNotification(.....);
});

*Note: I haven't tested that code, but it's along those lines.

gauntface avatar Apr 11 '17 13:04 gauntface

@gauntface Thanks for the reply! That didn't quite work for me but I went a different route inspired by your answer and it got the job done. Closing this

jemise111 avatar Apr 12 '17 20:04 jemise111

@jemise111 Would you like to post the solution for those of us with a similar problem?

chrisharrington avatar Dec 24 '17 16:12 chrisharrington

Hey @chrisharrington, I don't have access to the exact code anymore but IIRC it looks something like this:

Wherever you initialize your service worker:

this.messaging.onMessage(payload => {
   if (!document.hasFocus()) {
      serviceWorker.controller.postMessage({type: 'received_message_inactive_tab', payload});
    }
});

In your firebase-messaging-sw.js:

self.addEventListener('message', event => {
    if (event.data.type === 'received_message_inactive_tab') {
      const object = // turn payload into notifications object;
      self.registration.showNotification(object.title, object.options);
    }
});

Hope that helps!

jemise111 avatar Dec 27 '17 03:12 jemise111

It is really strange that this is not the default behaviour.

andidev avatar Nov 07 '18 20:11 andidev