I try to postMessage between a WebApp and the corresponding ServiceWorker. The serviceWoker is successfully registered and working so far.
Unfortunately I noticed some strange behavior:
1. The navigator.serviceWorker.controller is always null.
2. At the serviceWorker side I implemented postMessage this way:
self.addEventListener('message', function (evt) {
console.log('postMessage received', evt);
});
Unfortunately the important field to post back to origin evt.origin=““ and evt.source=null do not contain the desired values. But I always receive the sent evt.data.
Do you know how to post back?
Thank you very much!
Andi
@GalBracha was asking if you could communicate with the client without first sending a message - yes!. Here's a quick example of how I did it when I wanted to send a message to clients when a push notification was received (not when the user clicked on the notification, but when the service worker received the event):
in your client js (after service worker registration, etc):
in your service worker, in response to some event (perhaps the install event):
the trick is (obviously?) to attach your listener for the message event to the serviceWorker object, not the window object.
One way to send a response from the worker back to the controlled app is shown in this demo and is done the following way (I haven't actually tested this yet, but the demo works well and the code seems to agree with the specs).
In the main page:
And in the service worker code:
You should then be able to use the promise returned by the
sendMessage
function to do what you want with the response coming from the service worker.