Skip to content

Commit b4d5125

Browse files
committed
[sandbox] wait more reliably for sw init
1 parent 21442e2 commit b4d5125

File tree

2 files changed

+14
-33
lines changed

2 files changed

+14
-33
lines changed

packages/sandbox/controller.html

Lines changed: 5 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,9 @@
11
<title>Proxy Sandbox Controller</title>
22
<script>
3-
function notifyReady(controller) {
4-
parent.postMessage({ $sandboxsw$type: "ready" }, "*");
5-
}
6-
7-
function checkAndNotifyIfReady(registration) {
8-
const controller = navigator.serviceWorker.controller;
9-
if (!controller) return;
10-
11-
if (controller.state === "activated") {
12-
notifyReady(controller);
13-
} else {
14-
controller.addEventListener("statechange", function onStateChange() {
15-
if (controller.state === "activated") {
16-
console.log("state activated");
17-
controller.removeEventListener("statechange", onStateChange);
18-
notifyReady(controller);
19-
}
20-
});
21-
}
22-
}
23-
243
navigator.serviceWorker
254
.register("/sw.js", {
265
scope: "./",
276
})
28-
.then((registration) => {
29-
if (navigator.serviceWorker.controller) {
30-
// there's probably already a service worker
31-
checkAndNotifyIfReady(registration);
32-
} else {
33-
// there's no service worker, wait until we're controlled
34-
navigator.serviceWorker.addEventListener("controllerchange", () => {
35-
checkAndNotifyIfReady(registration);
36-
});
37-
}
38-
})
397
.catch((error) => {
408
console.error("Service Worker registration failed:", error);
419
window.parent.postMessage(
@@ -54,4 +22,9 @@
5422
// forward messageport
5523
navigator.serviceWorker.controller.postMessage(event.data, event.ports);
5624
});
25+
navigator.serviceWorker.addEventListener("message", (event) => {
26+
if (event.data === "ready") {
27+
window.parent.postMessage({ $sandboxsw$type: "ready" }, "*");
28+
}
29+
});
5730
</script>

packages/sandbox/sw.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,16 @@ self.addEventListener("install", () => {
1010
self.skipWaiting();
1111
});
1212

13+
async function notify() {
14+
let clients = await self.clients.matchAll();
15+
for (let client of clients) {
16+
client.postMessage("ready");
17+
}
18+
}
19+
1320
self.addEventListener("activate", (e) => {
14-
e.waitUntil(self.clients.claim());
21+
e.waitUntil(self.clients.claim().then(notify));
1522
});
1623

1724
console.log("sw initialized");
25+
notify();

0 commit comments

Comments
 (0)