我正在使用pushy.me服务来接收推送通知,并且我将所有设置正确。所以现在我收到了推送服务提供者文件,并且可以在控制台中显示它,但问题是我必须在我的React Compoonents中访问推送数据,所以我该如何导出服务工作者中经过整理的数据并从中访问我的react组件或任何其他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));
}
});
答案 0 :(得分:0)
Service Worker和常规JavaScript执行上下文之间可用的通信渠道是postMessage。您将postMessage事件侦听器附加到客户端代码(React代码)中,然后从Service Worker发送消息。
https://developer.mozilla.org/en-US/docs/Web/API/Client/postMessage