28

I am prototyping browser push notifications with FCM. I just copied the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging). Messages are recieved and displayed as they should be. But when I try to modify the message in the Service Worker (messaging.setBackgroundMessageHandler) nothing happens. The service worker is called, and if I implement an event listener in that service worker for the push notifications, it catches the event. But the method setBackgroundMessageHandler is never called. I am trying this on Chrome 54.

Any ideas what I need to do to customize the message in the service worker?

Thank you very much!

Mathias
  • 1,076
  • 1
  • 9
  • 10

6 Answers6

51

For anyone experiencing the same problem, here is the answer: https://github.com/firebase/quickstart-js/issues/71

short summary: do not include a "notification" element in your json message.

Mathias
  • 1,076
  • 1
  • 9
  • 10
10

This is a solution that worked for me in a webapp. It displays the notification with title and body text along with an image and handles the user click.

firebase-messaging-sw.js

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

// Initialize Firebase
var config = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  databaseURL: 'YOUR_DB_URL',
  projectId: 'YOUR_PROJ_ID',
  storageBucket: 'YOUR_STORAGE_BUCKET',
  messagingSenderId: 'YOUR_SENDER_ID',
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
  console.log('Handling background message ', payload);

  return self.registration.showNotification(payload.data.title, {
    body: payload.data.body,
    icon: payload.data.icon,
    tag: payload.data.tag,
    data: payload.data.link,
  });
});

self.addEventListener('notificationclick', function (event) {
  event.notification.close();
  event.waitUntil(self.clients.openWindow(event.notification.data));
});

JSON Message

{
  "message": {
    "token": "YOUR_TARGET_APP_TOKEN",
    "data": {
      "title": "FCM Message",
      "body": "This is an FCM Message",
      "icon": "https://shortcut-test2.s3.amazonaws.com/uploads/role_image/attachment/10461/thumb_image.jpg",
      "link": "https://yourapp.com/somewhere"
    }
  }
}
Alex Chebotarsky
  • 481
  • 5
  • 19
Sparm
  • 529
  • 1
  • 6
  • 14
3

As mentioned by others, including notification in the payload stops it working on the web JS SDK, however you need it present for it to work in native apps.

The workaround I found for the web was to use the web browser native EH push to handle the event manually:

https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onpush

  self.addEventListener('notificationclick', function(event) {
    console.log('SW: Clicked notification', event)

    let data = event.notification.data

    event.notification.close()

    self.clients.openWindow(event.notification.data.link)
  })

  self.addEventListener('push', event => {
    let data = {}

    if (event.data) {
      data = event.data.json()
    }

    console.log('SW: Push received', data)

    if (data.notification && data.notification.title) {
      self.registration.showNotification(data.notification.title, {
        body: data.notification.body,
        icon: 'https://example.com/img/icons/icon-144x144.png',
        data
      })
    } else {
      console.log('SW: No notification payload, not showing notification')
    }
  })
Titan
  • 5,567
  • 9
  • 55
  • 90
  • For me neither messaging.setBackgroundMessageHandler() nor messaging.onMessage() was getting called. With your workaround I finally got console messages upon receiving notification – kapil pandey Jun 09 '20 at 06:29
1

When you try to send a push message are you doing it while your app is on focus or not? Because from the documentation, it says that setBackgroundMessageHandler is only called when the Web app is closed or not in browser focus.

Based on the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging).

If your app is in focus: the push message is received via messaging.onMessage() on the index.html
If your app does not have focus : the push message is received via setBackgroundMessageHandler() on teh service worker file.

River Paul
  • 124
  • 1
  • 8
  • Sorry. Forgot to mention this: on focus it works well and onMessage method is called and I can do what I want with the message. When the page has no focus, the notification is displayed but I cannot customize it within the setBackgroundMessageHandler method as it is never called. – Mathias Nov 07 '16 at 11:24
0

setBackgroundMessageHandler will be called always in both ios and android In iOS, if app state is quit or killed It is refreshed after few minutes. Make sure to send content_available : true in the payload

{
     "registration_ids":["token"],
     "collapse_key" : "packageName",
     "notification" : {
         "body" : "Body of Your Notification",
         "title": "Title of Your Notification",
         "sound": "default"
     },
     "priority": "high",
     "content_available": true, // This is compulsory for background handler
     "data" : {
         "body" : "Body of Your Notification in Data",
         "title": "Title of Your Notification in Title",
         "badge": 89
     }
}
Manish Arora
  • 397
  • 3
  • 12
0
messaging().setBackgroundMessageHandler(async remoteMessage => {
       console.log('Message handled in the background!', remoteMessage);
          });

This one fixed mine issue.

Dev Gaud
  • 676
  • 6
  • 10