0

Below is my fcm setBackgroundMessageHandler function:

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };
var event = new CustomEvent("name-of-event", payload);

// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);
  return self.registration.showNotification(notificationTitle,
      notificationOptions);
});

I am unable to access document in above method. I have tried to save document in global variable and access it inside above method but it does not work.

var document = document;
.
.
.
document.dispatchEvent(event); // gives error: dispatchEvent of undefined
Ajit Soman
  • 3,926
  • 3
  • 22
  • 41
  • 1
    As far as I know your background handler runs in a service worker, which doesn't have access to the DOM. You use `postMessage()` to send messages between the service worker and the main page though. See https://stackoverflow.com/questions/37704641/access-dom-by-web-worker – Frank van Puffelen Dec 28 '17 at 16:07
  • @FrankvanPuffelen Thanks – Ajit Soman Dec 28 '17 at 17:00
  • @FrankvanPuffelen is there any way to prevent notification in `setBackgroundMessageHandler` – Ajit Soman Dec 29 '17 at 14:27

1 Answers1

2

Since document is not accessible in service worker. So there is no way to use its dispatchEvent function to emit event to Main page.

To Send message from service worker to Main page we can use BroadcastChannel. In Main page create a listener like this:

var listener = new BroadcastChannel('listener');
listener.onmessage = function(e) {
  console.log('Got message from service worker',e);
};

In service worker js file use BroadcastChannel 's postMessage function to send message to main page:

var listener = new BroadcastChannel('listener');
listener.postMessage('It works !!');
Ajit Soman
  • 3,926
  • 3
  • 22
  • 41