fgerschau / comments

1 stars 0 forks source link

how-to-communicate-with-service-workers/ #9

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

How to communicate with Service Workers

This article gives you an overview of the MessageChannel, Broadcast API and Client API and helps you to decide which one to use.

https://felixgerschau.com/how-to-communicate-with-service-workers/

Kamikotomushoo commented 3 years ago

how i can get the access to clients array? cuz in my file i cann't doing like that

fgerschau commented 3 years ago

Hey, it's hard to tell without knowing your code. My guess is that you're not accessing it from within the service worker (in the article service-worker.js).

Remember that you have to register the service worker like that:

navigator.serviceWorker.register('/service-worker.js');

Then you should be able to access the clients via self.clients. This is not supported on Safari and IE though (https://developer.mozilla.org/en-US/docs/Web/API/Clients).

rajneesh44 commented 3 years ago

I am unable to navigate while using client.navigate(url) Response is coming as Uncaught (in promise) TypeError: This service worker is not the client's active service worker.

fgerschau commented 3 years ago

Hey @rajneesh44, try leaving out includeUncontrolled when calling clients.matchAll.

Apparently, you are accessing a service worker that is not controlling the page.

rajneesh44 commented 3 years ago

Hello @fgerschau I tried what you said, but now I am unable to focus on my tab when i click on action button of push notification using client.focus(). When I include includeUncontrolled : true, I am able to use client.focus() but client.navigate(url) is not working. Please guide me.

fgerschau commented 3 years ago

@rajneesh44 maybe you need to call client.focus() first (and wait for the promise to resolve). I think the issue is that you can't call .navigate on a client that's not focused. You need to add includeUncontrolled: true in this case.

So your code looks something like this:

await client.focus();
client.navigate(url);

If you have further questions, feel free to email me.

luca-viggiani commented 3 years ago

Great and very useful tutorial, thanks!