messageSW.js 1.0 KB

1234567891011121314151617181920212223242526272829303132
  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.js';
  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. * @memberof module:workbox-window
  21. */
  22. function messageSW(sw, data) {
  23. return new Promise((resolve) => {
  24. const messageChannel = new MessageChannel();
  25. messageChannel.port1.onmessage = (event) => {
  26. resolve(event.data);
  27. };
  28. sw.postMessage(data, [messageChannel.port2]);
  29. });
  30. }
  31. export { messageSW };