当浏览器或PWA在后台运行时,FCM推送通知会显示两次

时间:2019-06-12 15:58:11

标签: push-notification service-worker progressive-web-apps

我已经设置了推送通知,以在台式机浏览器和移动浏览器(作为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);
            }
          });
      }

0 个答案:

没有答案