Yêu cầu thg 5 23, 2019 9:03 SA 163 0 1
  • 163 0 1
0

Xử lý sự kiện click trong Firebase

Chia sẻ
  • 163 0 1

Xin chào, mình đang làm một cái module nhỏ tích hợp Firebase với nhiệm vụ như sau: để push message từ server về các subscriber là client browser, tuy nhiên đang gặp vấn đề sau:

Dữ liệu truyền dạng sử dụng Notification message

Đối với trường hợp App ở background thì không set requireInteraction được

Trường hợp App ở Foreground thì lại không set click url được.

Rất mong được sự hỗ trợ từ các bạn!

Dưới đây là 2 trường hợp xử lý ở client

//dữ liệu:
{
  "notification": {
    "title": "Title test",
    "body": "This is body content",
    "icon": "favicon.png",
    "click_action": "https://abc.com"
  },
  "to": "<client_browser_token_id>" 
}

//background
messaging.setBackgroundMessageHandler(function(payload) {
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: payload.notification.icon,
    click_action: payload.notification.click_action,
    requireInteraction: true
  };

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

//foreground
self.addEventListener('push', function(event) {
  var data = event.data.json();
  var title = data.notification.title;  
  var body= data.notification.body;
  var icon = data.notification.icon;
  var click = data.notification.click_action;
    self.registration.showNotification(title, {
      body: body,
      icon: icon,
      click_action : click,
      requireInteraction: true
  });
}); 

1 CÂU TRẢ LỜI


Đã trả lời thg 5 29, 2019 2:30 SA
Đã được chấp nhận
0

Mình đã xử lý được theo cách sau:

self.addEventListener('push', function(event) {
  var data = event.data.json();

  event.waitUntil(
    self.registration.showNotification(data.notification.title, {
      body: data.notification.body,
      icon: data.notification.icon,
      requireInteraction: true,
      data: {
        url: data.notification.click_action
      }
    })
  );
}); 

self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    var url = event.notification.data.url;
    console.log(url, event.notification.data);
    event.waitUntil(
        clients.matchAll({
                type: 'window'
            })
            .then(function(windowClients) {
                for (var i = 0; i < windowClients.length; i++) {
                    var client = windowClients[i];
                    if (client.url === url && 'focus' in client) {
                        return client.focus();
                    }
                }
                if (clients.openWindow) {
                    return clients.openWindow(url);
                }
            })
    );
});

Chia sẻ
Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí