Push-уведомления не настраиваются - PullRequest
1 голос
/ 03 мая 2019

Существует некоторая проблема в настройке push-уведомлений.

setOnMessage() {
        this.init();
        this.checkPermission();
        this.firebase.messaging().onMessage(function(payload) {
            if (!("Notification" in window) || !("notification" in payload))
                 return false;                
            let data = payload.notification;
            let options = {
                body: data.body,
                icon: '/icons/android-icon-48x48.png',
                requireInteraction: true
            };
            let notification = new Notification(data.title, options);
            setTimeout(() => {
                notification.close();
            }, 10000);
            notification.onclick = () => {
                //...
            }
        })
    },

Этот код отлично работает, когда текущее окно браузера сфокусировано на странице хоста. Но если это окно закрыто (или даже сфокусировано на другой вкладке браузера), то отображается уведомление по умолчанию (поэтому обработчик события «onclick» не работает). Пожалуйста, помогите, извините за мой английский.

1 Ответ

1 голос
/ 06 мая 2019

Да, на стороне локального сервера есть работник службы "firebase-messaging-sw.js":

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/5.11.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.11.1/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
    'messagingSenderId': '1234'
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // Customize notification here
    var data = payload.notification;
    var options = {
      body: data.body,
      icon: '/icons/android-icon-48x48.png',
      requireInteraction: true
    };
    return self.registration.showNotification(data.title, options);
});
...