messageSW.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  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 workbox-window
  21. */
  22. // Better not change type of data.
  23. // eslint-disable-next-line @typescript-eslint/ban-types
  24. function messageSW(sw, data) {
  25. return new Promise((resolve) => {
  26. const messageChannel = new MessageChannel();
  27. messageChannel.port1.onmessage = (event) => {
  28. resolve(event.data);
  29. };
  30. sw.postMessage(data, [messageChannel.port2]);
  31. });
  32. }
  33. export { messageSW };