Alan Bir
Alan Bir

Reputation: 33

service-worker.js not able to send messages to ui.js

I have a service-worker.js that has a post-message function that reads:

function postMsg(msg) {
    if (self.clients && self.clients.matchAll) {
        self.clients.matchAll().then(clients => {
            clients.forEach(client => {
                client.postMessage(msg);
            });
        }).catch(error => {
            console.error(' Error matching clients:', error);
        });
    } else {
        console.error('self.clients or self.clients.matchAll is not available');
    }

and

self.addEventListener('activate', event => {
    event.waitUntil(
        (async () => {
            try {
                console.log('123:claiming');
                await self.clients.claim();

and

window.addEventListener('load', function () {
     if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/service-worker.js', {
                scope: '/'
            }).then(function(registration) {
                console.log('registering service-worker');

But although I see the 123:claiming message, this seems to be before the page loads and therefore when I do a postMsg() then the self.clients is undefined.

How should I be setting up self.clients in this case (so that my service-worker can send messages to my ui)?

Upvotes: 1

Views: 48

Answers (0)

Related Questions