From fde90f3ec150372e7a426720833262c5fe02c841 Mon Sep 17 00:00:00 2001 From: Toshit Chawda Date: Mon, 8 Jul 2024 12:02:28 -0700 Subject: [PATCH] tell the sw to refresh its port when a new shared worker gets made --- src/connection.ts | 11 ++++++++--- src/worker.ts | 5 ++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/connection.ts b/src/connection.ts index 37167f5..2bcdfc8 100644 --- a/src/connection.ts +++ b/src/connection.ts @@ -32,8 +32,8 @@ export type WorkerResponse = { error?: Error, } -type BroadcastMessage = { - type: "getPath" | "path", +export type BroadcastMessage = { + type: "getPath" | "path" | "refreshPort", path?: string, } @@ -89,8 +89,13 @@ export class WorkerConnection { // @ts-expect-error if (self.clients) { // running in a ServiceWorker - // ask a window for the worker port + // ask a window for the worker port, register for refreshPort this.port = searchForPort(); + this.channel.onmessage = (event: MessageEvent) => { + if (event.data.type === "refreshPort") { + this.port = searchForPort(); + } + } } else if (workerPath && SharedWorker) { // running in a window, was passed a workerPath // create the SharedWorker and help other bare-mux clients get the workerPath diff --git a/src/worker.ts b/src/worker.ts index e62e415..816a896 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -1,9 +1,12 @@ import { BareTransport } from "./baretypes"; -import { WorkerMessage, WorkerResponse } from "./connection" +import { BroadcastMessage, WorkerMessage, WorkerResponse } from "./connection" let currentTransport: BareTransport | null = null; let currentTransportName: string = ""; +const channel = new BroadcastChannel("bare-mux"); +channel.postMessage({ type: "refreshPort" }); + function noClients(): Error { // @ts-expect-error mdn error constructor: new Error(message, options) return new Error("there are no bare clients", {