简体   繁体   中英

Customize notification from firebase cloud messaging running in background handler

How can I customize the notification that is created by the background handler for Firebase in a web application?

Some of the sample codes, with my edits, is shown below:

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);

  // Customize notification here
  const data = payload.data;
  const click_action = "https://www.google.com";
  const notificationTitle = data.title;
  const notificationOptions = {
    "body": data.body,
    "icon": "icon.png",
    "click_action": click_action
  };

  const timeout = data.timeout;

  // var n = new Notification(notificationTitle, notificationOptions);
  // n.onclick = function () {
  //   if (click_action !== null) {
  //     window.open(click_action);
  //   }
  // };
  // setTimeout(n.close.bind(n), 5000);

  return self.registration.showNotification(notificationTitle, notificationOptions);
});

I would like to set the timeout option. When I'm creating a notification in a content script, I use the commented out code which allows me to specify a timeout. However, I can't apply the same technique here.

I would also like to customize the click action. Specifying the click_action key in the notification options object doesn't do anything for me. In a content script, I would add an onClickListener.

Overall, I need a way to add a click listener and customize the timeout duration.

By adding "time_to_live" : 3 to your JSON payload this specifies the lifespan of a message in FCM.

You can see more details on this at https://firebase.google.com/docs/cloud-messaging/concept-options#ttl

Hope this helps

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