2017-08-01 116 views
0
var config = { 
    messagingSenderId: "18????????2" 
}; 
firebase.initializeApp(config); 
const messaging = firebase.messaging(); 

messaging.setBackgroundMessageHandler(function (payload) { 

    $.ajax({ 
     type: "POST", 
     dataType: "json", 
     data: { notificationID: payload.data.notificationID }, 
     url: "https://myapi/somerestservice", 
     success: function (data) { 
      console.log("remove notification status : " + data.Status + " - Message : " + data.Message); 
     } 
    }); 
    const notificationTitle = payload.notification.title; 
    const notificationOptions = { 
     body:payload.notification.body, 
    }; 
    return self.registration.showNotification(notificationTitle, notificationOptions); 

我收到的背景信息沒有任何錯誤和消息代碼將出現在瀏覽器中完美FCM serviceworker收到背景消息,但不執行

我的問題是我需要execute一些代碼從db刪除數據,但任何代碼我在setBackgroundMessageHandler添加時接收到消息 沒有被解僱是有當背景 收到消息的任何觸發的事件(在前臺我用onMessage及其工作不錯)

回答

0

如果notification科當您發送HTTP/XMPP請求時(例如,從後端),將不會調用註冊爲setBackgroundMessageHandler的消息處理程序。 Firebase將爲您處理該信息並按原樣顯示。

如果您需要在應用程序處於後臺時收到消息時執行某些操作,則可以在消息中使用data鍵;如果省略notification鍵,用setBackgroundMessageHandler註冊的處理程序將被調用,您可以處理的有效載荷和自定義通知:

messaging.setBackgroundMessageHandler(function(payload) { 
    console.log('[firebase-messaging-sw.js] Received background message ', payload); 

    // Do you AJAX request here. 

    // Customize and show your notification 
    const notificationTitle = payload.data.title, 
    const notificationOptions = { 
    body: payload.data.body, 
    icon: payload.data.icon 
    }; 

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

注意:除了自己顯示通知,您也將有手動處理點擊和關閉事件。

要發送的消息:

https://fcm.googleapis.com/fcm/send 
Content-Type:application/json 
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA 

{ "data": { 
    "title": "Hello", 
    "body": "How are you?", 
    "icon": "https://..." 
    }, 
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." 
} 

官方文檔的這部分可以是一個有點混亂,但什麼時候這兩個消息處理程序調用一些澄清可以在這裏找到:https://sentinelstand.com/article/handling-firebase-notification-messages-in-your-web-app