Bruno Matavelli
Bruno Matavelli

Reputation: 189

Firebase push notifications click does not work

I am having problems to implement notifications using firebase. The click event does not work. I am using the HTTP 1 version sending the bearer token.

{
  "message": {
    "token": "8888****usertoken****8888",
    "notification": {
      "title": "Background Message Title",
      "body": "Background message body"
    },
    "webpush": {
      "fcm_options": {
        "link": "https://dummypage.com"
      }
    }
  }
}

I have also tried click_action, action, and many other variations that just did not work.

I am using version 8.0.0

According to the documentation found on this link https://firebase.google.com/docs/cloud-messaging/js/send-multiple, I should be able to implement it using fcm_options.

I tried a workaround implementing messaging.onBackgroundMessage, but when I implement this method and use self.registration.showNotification, the notification is displayed twice. one triggered by the browse and the other by this code.

Registering self.addEventListener('notificationclick' only seems to work when I implement onBackgroundMessage.

I followed the documentation, but it is driving me crazy.

This is my service worker code:

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

var firebaseConfig = {
    apiKey: "xxxxxx",
    authDomain: "xxxxxxxx.firebaseapp.com",
    databaseURL: "https://xxxxxx.firebaseio.com",
    projectId: "xxx-xxx",
    storageBucket: "xxx-xxx.appspot.com",
    messagingSenderId: "222222222",
    appId: "1:2222:web:22222"
};
console.log("fire base messaging")

firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();


messaging.onBackgroundMessage(function (payload) {
    console.log("onBackgroundMessage", payload)
    var dataFromServer = payload.notification;
    var notificationTitle = dataFromServer.title;
    var notificationOptions = {
        body: dataFromServer.body,
        image: dataFromServer.image,
        data: {
            url: "https://google.com"
        }
    };
    return self.registration.showNotification(notificationTitle,
        notificationOptions);
});

////Code for adding event on click of notification
self.addEventListener('notificationclick', function (event) {
    console.log("notificationclick", event)
    var urlToRedirect = event.notification.data.url;
    event.notification.close();
    event.waitUntil(self.clients.openWindow(urlToRedirect));
});

Upvotes: 5

Views: 11012

Answers (3)

dev-jeff
dev-jeff

Reputation: 311

Notifications are working using legacy API but unfortunately clicking the notification still does nothing. This is my code for sending the notification.

var notification = {
  'title': title,
  'body': body,
  'icon': 'hourglass.png',
  'click_action': router.resolve(route).href
}
var payload = {
  'notification': notification,
  // 'webpush': {
  //   'fcm_options': {
  //     'link': '/' + router.resolve(route).href
  //   }
  // }
}
if(registrationIds.length == 1) {
  payload['to'] = registrationIds[0]
} else if( registrationIds.length > 1){
  payload['registration_ids'] = registrationIds
}
return new Promise((resolve, reject) => {

  if (registrationIds.length) {
    fetch('https://fcm.googleapis.com/fcm/send', {
      'method': 'POST',
      'headers': {
        'Authorization': 'key=' + key,
        'Content-Type': 'application/json'
      },
      'body': JSON.stringify(payload)
    }).then(function(response) {
      resolve(true)
    }).catch(function(error) {
      console.error('sendNotification error', error);
      reject(false)
    })

  }
  else {
    console.log('This timer has no registered clients.')
    reject(false)

  }

})

Edit: I think most of my confusion stemmed from finding examples with the V1 API and mixing them up with the legacy API. I needed click_action instead of the fcm_options.link in the payload. I updated my code and is now working as intended.

Upvotes: 1

Bruno Matavelli
Bruno Matavelli

Reputation: 189

Turns out I was passing an entire URL to webpush.fcm_options.link = "https://google.com", all I had to do was to pass only the relative path like webpush.fcm_options.link = "/mypage".

So the request to send would be like this:

{
  "message": {
    "token": "8888****usertoken****8888",
    "notification": {
      "title": "Background Message Title",
      "body": "Background message body"
    },
    "webpush": {
      "fcm_options": {
        "link": "/mypage" 
      }
    }
  }
}

I don't see in the docs say it is only the relative path. It even states that HTTPS is required. I spent a few hours on this one, I hope it helps somebody else.

https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#WebpushFcmOptions

Upvotes: 13

I was having the same issue. I added a notificationclick event handler. You can use the data param in the notification event to open a new tab or focus an already opened one.

The code you already have is fine, now adding the listener looks like this:

// messaging.onBackgroundMessage(...);

function handleClick (event) {
  event.notification.close();
  // Open the url you set on notification.data
  clients.openWindow(event.notification.data.url)
}
self.addEventListener('notificationclick', handleClick);

This resources might be helpful

Upvotes: 2

Related Questions