怎么在 push callback 里向 main script 发 message? service-worker.js
console.log("Service Worker Loaded...");
self.addEventListener("push", e => {
const data = e.data.json();
console.log("Push Recieved...");
// post data back to main script
});
1
lbfeng OP 我自己挖的坑自己填吧。
service worker 可以得到所有的 clients 也就是所有 register 过这个 service worker 的 script. ```javascript function sendMessage(message) { return self.clients.matchAll({ includeUncontrolled: true // https://developer.mozilla.org/en-US/docs/Web/API/Clients/matchAll }).then(clients => { // post messages // only has one client clients[0].postMessage(message); }); } ``` 在 push event 的 callback function 里调用 sendMessage 就可以吧 remote push message 传回 client. |