Push-уведомление FCM отображается дважды, когда браузер или PWA находятся в фоновом режиме - PullRequest
0 голосов
/ 12 июня 2019

Я установил push-уведомления, которые будут отображаться в настольных браузерах и мобильных браузерах (как PWA), уведомления приходят нормально, если браузер находится на переднем плане.

Проблема начинается, если браузер или PWAв фоновом режиме: уведомление приходит дважды, один стилизованный с изображением и другими настройками, а другой имеет только заголовок и текст сообщения.

Я попытался добавить теги безуспешно.

Я будублагодарю за любую помощь

Работник службы:

self.addEventListener('fetch', function(event) {
    event.respondWith(
        caches.match(event.request).then(function(response) {
            return response || fetch(event.request);
        })
    );
});

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

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

const messaging = firebase.messaging();

//Notificación con push event. Muestra la notificación dos veces
self.addEventListener('push', function(event) {
  var data = {};
  if (event.data) {
    data = event.data.json();
  }
  console.log('[Service Worker] Push Received.');
  console.log(`[Service Worker] Push had this data: "${event}"`);
  console.log(data.notification);

  const title = data.notification.title;
  const options = {
    body: data.notification.body,
    icon: 'images/corporative/logo/favicon-96x96.png',
    tag: "notification-1",
    badge: 'images/corporative/logo/favicon-96x96.png'
  };

   event.waitUntil(self.registration.showNotification(title, options));
});

//Cick en la notificación
self.addEventListener('notificationclick', function(event) {
  console.log('[Service Worker] Notification click Received.');
  event.notification.close();
  event.waitUntil(
    clients.openWindow('............')
  );
});

Клиентская сторона:

       var config = {
        apiKey: ".............",
        authDomain: "..........",
        databaseURL: ".........",
        projectId: "..........",
        storageBucket: ".........",
        messagingSenderId: "......."
      };

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

      messaging.usePublicVapidKey(".....");
      messaging.requestPermission().then(function() {

        if (isTokenSentToServer()) {
          console.log('Token already sent to server (saved)');
        } else {
          getRegToken();
        }

      }).catch(function(err) {
        console.log('Unable to get permission to notify.', err);
      });

      function getRegToken(argument) {

      messaging.getToken().then(function(currentToken) {
        if (currentToken) {
          sendTokenToServer(currentToken);
          setTokenSentToServer(true); //false
          console.log(currentToken);
          //updateUIForPushEnabled(currentToken);
        } else {
          // Show permission request.
          console.log('No Instance ID token available. Request permission to generate one.');
          // Show permission UI.
          //updateUIForPushPermissionRequired();
          setTokenSentToServer(false);
        }
      }).catch(function(err) {
        console.log('An error occurred while retrieving token. ', err);
        showToken('Error retrieving Instance ID token. ', err);
        setTokenSentToServer(false);
      });
      }

      function setTokenSentToServer(sent) {
        window.localStorage.setItem('sentToServer', sent ? 1 : 0);
      }

      function isTokenSentToServer() {
        return window.localStorage.getItem('sentToServer') == 1
      }

      // Callback fired if Instance ID token is updated.
      messaging.onTokenRefresh(function() {
        messaging.getToken().then(function(refreshedToken) {
          console.log('Token refreshed.');
          setTokenSentToServer(false);
          // Send Instance ID token to app server.
          sendTokenToServer(refreshedToken);
          // ...
        }).catch(function(err) {
          console.log('Unable to retrieve refreshed token ', err);
          showToken('Unable to retrieve refreshed token ', err);
        });
      });

      function sendTokenToServer(currentToken) {
        $.ajax({
            dataType: 'json',
            type: 'POST',
            url: 'pushToken',
            data: { push_token:currentToken, device_type:'web' },
            success: function (response) {
              console.log(response);
            }, error: function (response) {
              console.log(response);
            }
          });
      }
...