admin管理员组

文章数量:1357707

Today we can find many examples of sending message from a service worker to a client, but always following the reception of a message event in the service worker.

I would like to know if we can send messages independently of this event? And if yes, how? I tried few things, without success...

In my case, it's for redirect a client to a new page when my service worker receives a push event.

Today we can find many examples of sending message from a service worker to a client, but always following the reception of a message event in the service worker.

I would like to know if we can send messages independently of this event? And if yes, how? I tried few things, without success...

In my case, it's for redirect a client to a new page when my service worker receives a push event.

Share Improve this question edited Jun 3, 2015 at 15:09 Jeff Posnick 56.2k14 gold badges149 silver badges174 bronze badges asked Jun 3, 2015 at 11:21 Mathieu Le BihanMathieu Le Bihan 531 silver badge7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

client.js :

const swListener = new BroadcastChannel('swListener');
swListener.onmessage = function(e) {
  console.log('swListener Received', e.data);
};

service-worker.js

  const swListener = new BroadcastChannel('swListener');
   swListener.postMessage('This is From SW');

The interface for Client.postMessage() is described at https://github./slightlyoff/ServiceWorker/issues/609. Unfortunately, it is not fully implemented in Google Chrome as of version 45, though I'd expect it to make it into a version at a later date.

When the functionality's available, you could use self.clients.matchAll() to obtain a list of any open pages that are being controlled by the service worker, and call the postMessage() method on the specific client that you care about. You need to keep in mind that it's entirely possible that there won't be any tabs open with a page controlled by your service worker, in which case you'd want to do something like open a new client page with your target URL.

But, there's a method that's probably more appropriate for your use case (though also not currently support in Chrome 45): WindowClient.navigate(), which will instruct an open tab controlled by your service worker to navigate to a different URL on the same origin.

本文标签: javascriptPosting messages from a service worker to a client pageStack Overflow