Reputation: 6546
I am trying to setup this example and make it work however on the most simple one script file and one worker file it never sends a message to client from service worker. What can be the issue ?
Google Chrome Version 64.0.3282.167 (Official Build) (64-bit)
navigator.serviceWorker.addEventListener('message', event => {
console.log(event.data.msg, event.data.url);
});
navigator.serviceWorker.register("sw.js")
.then(function (registration) {
console.log("ServiceWorker registration successful with scope: ", registration.scope);
})
.catch(function (error) {
console.error("Service Worker Error", error);
});
addEventListener('install', event => {
event.waitUntil(self.skipWaiting());
});
addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
addEventListener('fetch', event => {
event.waitUntil(async function() {
// Exit early if we don't have access to the client.
// Eg, if it's cross-origin.
if (!event.clientId) return;
// Get the client.
const client = await clients.get(event.clientId);
// Exit early if we don't get the client.
// Eg, if it closed.
if (!client) return;
// Send a message to the client.
client.postMessage({
msg: "Hey I just got a fetch from you!",
url: event.request.url
});
}());
});
I console.log
in every place and the method client.postMessage
is being called.
This works on Mozilla Firefox Quantum 58.0.2 (64-bit)
Upvotes: 4
Views: 5162
Reputation: 18555
You must get the client object first. Add this inside your fetch
listener.
self.clients.matchAll().then(function (clients){
clients.forEach(function(client){
client.postMessage({
msg: "Hey I just got a fetch from you!",
url: event.request.url
});
});
});
Upvotes: 4