PWA推送通知。消息仅出现在控制台中。

时间:2018-03-12 13:33:32

标签: javascript html firebase firebase-cloud-messaging

最后我接近终点线。我可以通过Firebase发送和接收推送通知。但是消息只在控制台日志中可见(应该是很好的通知对话框)。

控制台日志中的消息:

onMessage:  
{data: {…}, from: "493.......061", collapse_key: "do_not_collapse"}
collapse_key
:
"do_not_collapse"
data
:
{title: "My title", body: "Message Body here", status: "Message Body here"}
from
:
"493........061"
__proto__
:
Object

我有两个带代码的文件:

sw.js
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/service-worker.js');
  });
}

 var config = {
    apiKey: "AIzaSyB8H.....................Lxdrz480",
    authDomain: "project-name.firebaseapp.com",
    databaseURL: "https://project-name.firebaseio.com",
    projectId: "project-name",
    storageBucket: "project-name.appspot.com",
    messagingSenderId: "49.........1061"
  };
  firebase.initializeApp(config);


  const messaging = firebase.messaging();

  messaging.requestPermission()
  .then(function() {
      console.log('Have permission');
      return messaging.getToken();
  })
  .then(function(token)
  {console.log(token); }
  )
.catch(function(err){
    console.log('Error Ocurred');
})


messaging.onMessage(
function(payload) {console.log('onMessage: ', payload);}

)

firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/4.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.10.1/firebase-messaging.js');

 var config = {
    apiKey: "...................",
    authDomain: "project-name.firebaseapp.com",
    databaseURL: "https://project-name.firebaseio.com",
    projectId: "project-name",
    storageBucket: "project-name.appspot.com",
    messagingSenderId: "493..........1"
  };
  firebase.initializeApp(config);


  const messaging = firebase.messaging();

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

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

对我而言,文件firebase-messaging.js似乎永远不会触发。

1 个答案:

答案 0 :(得分:1)

确保检查通知有效负载。它必须采用以下格式:

{
   notification: 
   {
       title: 'Notifications are cool',
       body: 'Know how to send notifications',
       icon: 'https://www.shareicon.net/data/256x256.png',
       vibrate: [100, 50, 100],
       data: 
       {
          url: 'https://images.com/image001.png' 
       }
   }
}

例如,如果您只是发送:

{
   title: 'Notifications are cool',
   body: 'Know how to send notifications'
}

该通知将显示在控制台中,但不作为推送通知显示。