From 2d92bea4a9754373027455494050110d91bd13fc Mon Sep 17 00:00:00 2001 From: Danilo Woznica Date: Thu, 25 Jul 2024 09:52:19 +0100 Subject: [PATCH] fix(sw): assign new channel port on reload (#1166) --- sandpack-client/src/clients/runtime/index.ts | 10 +++++++++- sandpack-react/src/presets/CustomSandpack.stories.tsx | 1 + 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/sandpack-client/src/clients/runtime/index.ts b/sandpack-client/src/clients/runtime/index.ts index e9fb0eee..b6bbcf8d 100644 --- a/sandpack-client/src/clients/runtime/index.ts +++ b/sandpack-client/src/clients/runtime/index.ts @@ -195,14 +195,18 @@ export class SandpackRuntime extends SandpackClient { } }; - this.iframe.onload = () => { + const sendMessage = () => { const initMsg = { $channel: CHANNEL_NAME, $type: "preview/init", }; iframeContentWindow.postMessage(initMsg, "*", [channel.port2]); + + this.iframe.removeEventListener("load", sendMessage); }; + + this.iframe.addEventListener("load", sendMessage); } private handleWorkerRequest( @@ -362,6 +366,10 @@ export class SandpackRuntime extends SandpackClient { */ if (message.type === "refresh") { this.setLocationURLIntoIFrame(); + + if (this.options.experimental_enableServiceWorker) { + this.serviceWorkerHandshake(); + } } this.iframeProtocol.dispatch(message); diff --git a/sandpack-react/src/presets/CustomSandpack.stories.tsx b/sandpack-react/src/presets/CustomSandpack.stories.tsx index 0c275d1a..ce5276ff 100644 --- a/sandpack-react/src/presets/CustomSandpack.stories.tsx +++ b/sandpack-react/src/presets/CustomSandpack.stories.tsx @@ -55,6 +55,7 @@ export const ExperimentalServiceWorker: React.FC = () => { `, }} options={{ + bundlerURL: "https://nqfrns-3000.csb.app/", experimental_enableServiceWorker: true, }} template="react"