Make JS code communicate with a ServiceWorker

Posted on 2020-08-18 in Programmation

If you need to send data from your JS code to your ServiceWorker, you can do it like this:

navigator.serviceWorker.register("./sw.js").then(registration => {
    registration.active.postMessage("Some message");
});

You can then rely on this code in the ServiceWorker to read the message:

self.addEventListener("message", event => {
    console.log(event.data); // This will log: Some message
});