Два идентичных сообщения принимаются одновременно с уведомлениями pu sh через FCM - PullRequest
0 голосов
/ 27 мая 2020

Я использую Vue. js и FCM для реализации уведомления WebPu sh. Однако, когда я тестирую его, я получаю одно уведомление от Firebase и ДВА ИДЕНТИФИКАЦИОННЫХ PU SH УВЕДОМЛЕНИЯ, которые получает клиент независимо от браузера или устройства.

Любая помощь будет принята с благодарностью!

Ниже приводится выдержка из JS.

const messaging = firebase.messaging();

function showNotification(data) {
    console.log(data);
    var title = data.notification.title;
    var tag = 'push';

    return self.registration.showNotification(title, {
        icon: data.notification.icon,
        body: data.notification.body,
        data: data.data,
        vibrate: [400,100,400],
        tag: tag
    });
}

self.addEventListener('install', (event) => {
    event.waitUntil(self.skipWaiting());
});

function receivePush(event) {

    console.log("receivePush");
    console.log(event.data.json());
    if(event.data) {
        data = event.data.json();
    }
    if('showNotification' in self.registration) {
        event.waitUntil(showNotification(data));
    }
}

function notificationClick(event) {
    event.notification.close();
    event.waitUntil(
        clients.openWindow(event.notification.data.url)
    );
    addClickCount(event.notification.data.record_id);
}

function addClickCount (record_id) {
    var api_url = 'https://' + location.host + '/_app/api/auth/push';
    fetch(api_url, {
        method: 'POST',
        mode: 'cors',
        headers: {
          'Accept': 'application/json',
          'content-type': 'application/json',
        },
        body: JSON.stringify({id: record_id}),
    })
    .then(response => response.text())
    .then(text => console.log(text));
}

self.addEventListener('push', receivePush, false);
self.addEventListener('notificationclick', notificationClick, false);

Ниже приводится выдержка из токена.

<template>
        <div class="column-btn">
          <div class="col">
            <div class="btn btn-white">
              <a
                href="javascript:void(0);"
                class="btnItem push-yes"
                style="background:none"
                >Yes</a
              >
            </div>
          </div>
          <div class="col">
            <div class="btn btn-white">
              <a
                href="javascript:void(0);"
                class="btnItem push-no"
                style="background:none"
                >No</a
              >
            </div>
          </div>
</template>

export default {
  methods: {
  },
  mounted() {
    var pData = this.$parent;
    var thisData = this;
    $(document).on('click', '.push-yes', function() {
      pData.permission_off();
      thisData.modalClose();
    });
    $(document).on('click', '.push-no', function() {
      thisData.modalClose();
    });
  },
};

1 Ответ

1 голос
/ 31 мая 2020

В FCM есть четкие шаги, какой код добавить в Service Worker firebase-messaging-sw. js (https://firebase.google.com/docs/cloud-messaging/js/receive):

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

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

Я реализовал как там написано и работает нормально :)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...