messageSW.mjs 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. /*
  2. Copyright 2019 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import './_version.mjs';
  8. /**
  9. * Sends a data object to a service worker via `postMessage` and resolves with
  10. * a response (if any).
  11. *
  12. * A response can be set in a message handler in the service worker by
  13. * calling `event.ports[0].postMessage(...)`, which will resolve the promise
  14. * returned by `messageSW()`. If no response is set, the promise will not
  15. * resolve.
  16. *
  17. * @param {ServiceWorker} sw The service worker to send the message to.
  18. * @param {Object} data An object to send to the service worker.
  19. * @return {Promise<Object|undefined>}
  20. *
  21. * @memberof module:workbox-window
  22. */
  23. const messageSW = (sw, data) => {
  24. return new Promise((resolve) => {
  25. let messageChannel = new MessageChannel();
  26. messageChannel.port1.onmessage = (evt) => resolve(evt.data);
  27. sw.postMessage(data, [messageChannel.port2]);
  28. });
  29. };
  30. export {messageSW};