So it turns out that you cannot actually call the method in SW from your application (due to lifecycle issues), so you need to use the PostMessage API to send serialized JSON messages (so no callbacks, etc. ) ,.
You can send a message to the management software with the following application code:
navigator.serviceWorker.controller.postMessage({'hello': 'world'})
In the SW code in combination with the following:
self.addEventListener('message', function (evt) { console.log('postMessage received', evt.data); })
As a result, on the SW console, you get the following:
postMessage received Object {hello: "world"}
Thus, by passing a message (JS object) that points to a function and the arguments that I want to call my event listener, we can get it and call the correct function in SW. To return the result to the application code, you also need to transfer the MessageChannel port to SW, and then respond via postMessage, for example, in the application that you created and sent via MessageChannel with data:
var messageChannel = new MessageChannel(); messageChannel.port1.onmessage = function(event) { console.log(event.data); };
and then you can answer through it with your Worker Worker in a message handler:
evt.ports[0].postMessage({'hello': 'world'});
owencm
source share