bij*_*lcm 5 javascript web-push firebase-cloud-messaging
尝试使用FCM实施Web推送通知。
我可以使用Firebase云消息传递库在浏览器上接收带有有效负载的推送消息。
以下是一个javascript代码段。
<script src="https://www.gstatic.com/firebasejs/3.5.1/firebase.js"> </script>
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.onMessage(function(payload){
console.log('onMessage',payload);
});
Run Code Online (Sandbox Code Playgroud)
如何捕获单击,关闭,显示等事件?
您可以通过将以下内容添加到您的 firebase-messaging-sw.js 文件来监听数据负载的通知点击:
self.addEventListener('notificationclick', function(event) {
event.notification.close();
// Do something as the result of the notification click
});
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方式监听通知关闭事件:
self.addEventListener('notificationclose', function(event) {
// Do something as the result of the notification close
});
Run Code Online (Sandbox Code Playgroud)
您应该知道,为了确保您的代码有时间完成运行,您需要将一个 promise 传递到event.waitUntil()在您的代码完成时解析,例如:
self.addEventListener('notificationclick', function(event) {
event.notification.close();
const myPromise = new Promise(function(resolve, reject) {
// Do you work here
// Once finished, call resolve() or reject().
resolve();
});
event.waitUntil(myPromise);
});
Run Code Online (Sandbox Code Playgroud)
您将知道何时显示通知是否是数据负载,因为您需要调用self.registration.showNotification()自己的代码,如下所示:
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);
});
Run Code Online (Sandbox Code Playgroud)
您无法检测何时为“通知”负载显示通知,因为 SDK 会在单击时处理显示通知和行为。
代码片段来自:
| 归档时间: |
|
| 查看次数: |
5803 次 |
| 最近记录: |