javascript - 当应用程序在后台时,如何让服务人员处理推送?
问题描述
我正在使用 firebaseGuzzleHTTP
从我的laravel
应用程序中向我的网站用户发送消息。据我了解,有两种处理推送的方法,一种是使用消息,另一种是将对象notification
包装在. 使用 FirebaseAPI,但这似乎并没有在后台运行。它仅在用户在最后几分钟内打开 PWA 时才有效。无论用户上次打开浏览器是什么时候,我都想向他们发送通知。我知道我应该为此使用 eventListener 并且我确实为它放置了代码,但我似乎总是收到 firebase API 通知(当网站最近打开时)或根本没有通知。notification
data
notification
push
这是我的 Firebase 消息处理程序
messaging.setBackgroundMessageHandler(function(payload) {
// Customize notification here
var recep = JSON.stringify(payload);
recep = JSON.parse(recep);
var notification = recep.notification;
//notification = JSON.stringify(notification);
message = JSON.parse(notification);
const notificationTitle = message.title;
const notificationOptions = {
body: message.body,
icon: message.icon,
badge: '/img/favicon.png',
click_action: messaging.click_action
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
这是我的服务人员消息或push
处理程序:
self.addEventListener('push', function(e) {
var body;
if (e.data) {
body = e.data.json().notification.body;
} else {
body = 'Alert from AppMate.Open the app to view details!';
}
var options = {
body: body,
icon: 'img/favicon.png',
badge: 'img/favicon.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: 1
},
actions: [
{action: 'ap-mate', title: 'Visit AppMate!'}
]
};
e.waitUntil(
self.registration.showNotification('Appmate Notification', options)
);
});
这是通过以下方式发送到端点的请求GuzzleHTTP
:
$message = [
'data' => [
'notification' => [
'title' => $title,
'body' => $body,
'icon' => 'img/favicon.png',
'badge' => 'img/favicon.png'
],
],
'notification' => [
'title' => $title,
'body' => $body,
'icon' => 'img/favicon.png',
'badge' => 'img/favicon.png',
'click_action' => $action
],
'to' => $reg_id
];
$client = new Client([
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'key='.$access_token,
]
]);
$response = $client->post('https://fcm.googleapis.com/fcm/send',
['body' => json_encode($message)]
);
return $response->getBody();
解决方案
推荐阅读
- java - 从 java 8 切换到 java 10 后 CPU 使用率显示很高
- excel - 使用相邻列中的值进行条件连接和自动填充
- python - Scrapy:ItemLoader,有人可以向我解释这个错误吗?
- pointers - 不了解如何在 Rust 中访问向量的元素
- javascript - 我使用过滤器对吗?我不知道为什么这个解决方案有效
- javascript - 如何找到全局变量的位置
- c# - .Net Core Resources 给出 null 而不是字符串
- vue.js - 仅为“/”路由(Nuxt JS)提供 404 - 共享主机部署
- c++ - 无法创建/采样 3D 纹理(Qt/OpenGL)
- java - org.hibernate.LazyInitializationException:无法初始化代理 - 没有会话 -