【问题标题】:Firebase message, onMessage not being invokedFirebase 消息,未调用 onMessage
【发布时间】:2018-04-27 20:12:13
【问题描述】:

这就是我调用发送消息的方式:

  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:

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

但它并没有进入上面的代码块。目前我正在测试应用程序何时打开并获得焦点。

【问题讨论】:

    标签: firebase-cloud-messaging


    【解决方案1】:

    Service Worker 也用于 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);
    });
    

    【讨论】:

    • 你是什么意思?您的示例中没有触发 onMessage 吗?
    • 此示例用于显示应用何时处于后台的通知。问题是关于使用 onMessage 方法更新前台应用程序。
    • 这不是问题的答案
    • 我认为诺曼所说的是 onMessage 需要设置 backgroundMessageHandler 才能使网站上的 onMessage 功能正常工作
    • 谢谢 Nemesarial。我认为这是正确的。我已经有一段时间没有这样做了。
    猜你喜欢
    • 2020-01-21
    • 2012-12-13
    • 1970-01-01
    • 2014-01-12
    • 2021-06-16
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 2020-12-27
    相关资源
    最近更新 更多