Firebase消息,未调用onMessage [英] Firebase message, onMessage not being invoked

查看:203
本文介绍了Firebase消息,未调用onMessage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我打电话发送消息的方式:

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

这是我的onMessage:

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.

推荐答案

服务工作者也用于onMessage:

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

这篇关于Firebase消息,未调用onMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆