简体   繁体   中英

how to export data received by event in service worker to react components

I am using pushy.me service to receive push notifications and I setup every thing right. so rgiht now I am receiving push in service worker file and i can show it in console, but the problem is that I must access the push's data in my react compoonents,so how can I export the fentched data in service worker and access it from my react components or any other js files?

I assume that I can throw another event inside service worker's event and receive it from any other component but I couldn't make It cause I'm really new to events!

this is service-worker.js file:

// 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));
  }
});

The communication channel available between Service Workers and regular JavaScript execution context is postMessage. You attach postMessage event listeners in the client code (React code) and then send messages from the Service Worker.

https://developer.mozilla.org/en-US/docs/Web/API/Client/postMessage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM