我正在使用 pushy.me 服务来接收推送通知,并且我将一切设置正确。所以现在我正在接收服务工作者文件中的推送,我可以在控制台中显示它,但问题是我必须在我的反应组件中访问推送的数据,所以我如何导出服务工作者中的 fenched 数据并从中访问它我的反应组件或任何其他 js 文件?
我假设我可以在服务人员的事件中抛出另一个事件并从任何其他组件接收它,但我无法做到,因为我对事件真的很陌生!
这是 service-worker.js 文件:
// Import Pushy Service Worker 1.0.3
// Listen for incoming push notifications
self.addEventListener("push", function(event) {
// Extract payload as JSON object, default to empty object
var data = event.data.json() || {};
console.log(data);
var e = new CustomEvent("build", { data });
// Extract notification image URL
var image = data.image || "https://sdk.pushy.me/web/assets/img/icon.png";
// Notification title and body
var title = data.title || "";
var body = data.message || "";
// Notification options
var options = {
body: body,
icon: image,
badge: image,
data: {
url: data.url
}
};
// Wait until notification is shown
event.waitUntil(self.registration.showNotification(title, options));
});
// Listen for notification click event
self.addEventListener("notificationclick", function(event) {
// Hide notification
event.notification.close();
// Attempt to extract notification URL
var url = event.notification.data.url;
// Check if it exists
if (url) {
// Open the target URL in a new tab/window
event.waitUntil(clients.openWindow(url));
}
});