Firebase message, onMessage not being invoked

試著忘記壹切 提交于 2019-12-24 08:48:05

问题


This is how I am calling sending message:

  sendMessage() {
    var key = 'VERY LONG KEY -dffdADFDFD-vdfDafd';
    var to = 'VERY LONG KEY -ADEWerew-vdfDafd';
    var notification = {
      'title': 'Portugal vs. Denmark',
      'body': '5 to 1'
    };

    fetch('https://fcm.googleapis.com/fcm/send', {
      'method': 'POST',
      'headers': {
        'Authorization': 'key=' + key,
        'Content-Type': 'application/json',
      },
      'body': JSON.stringify({
        'to': to,
        'notification': notification,
        'data': {
          'message': 'example'
        }
      })
    }).then(function (response) {
      console.log(response);
      response.json().then(function (result) {
        console.log(result);
      })
    }).catch(function (error) {
      console.error(error);
    })
  }

This is my onMessage:

  messaging.onMessage(function (payload) {
    console.log("Message received. ", payload);
  });

But it does not go into the above code block. Currently I am testing when the application is opened and it has focus.


回答1:


The service worker is also used for the onMessage:

/**
 * Check out https://googlechromelabs.github.io/sw-toolbox/ for
 * more info on how to use sw-toolbox to custom configure your service worker.
 */


'use strict';
//importScripts('./build/sw-toolbox.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');

firebase.initializeApp({
  'messagingSenderId': '147703423097'
});

const messaging = firebase.messaging();

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);
});


来源:https://stackoverflow.com/questions/50069657/firebase-message-onmessage-not-being-invoked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!