diff --git a/src/types.ts b/src/types.ts index 7425860..7d554ce 100644 --- a/src/types.ts +++ b/src/types.ts @@ -6,6 +6,8 @@ import { WebSocketBroadcastChannel } from "./web-socket-broadcast-channel.ts"; */ export interface BroadcastChannelIsh extends EventTarget { readonly name: string; + onmessage: ((ev: MessageEvent) => void) | null; + onmessageerror: ((ev: Event) => void) | null; postMessage(message: unknown): void; close(): void; } diff --git a/src/web-socket-broadcast-channel.ts b/src/web-socket-broadcast-channel.ts index 460ab84..941727b 100644 --- a/src/web-socket-broadcast-channel.ts +++ b/src/web-socket-broadcast-channel.ts @@ -32,15 +32,23 @@ const log0: Logger = logger(import.meta.url); */ export class WebSocketBroadcastChannel extends EventTarget implements BroadcastChannelIsh { + onmessage: ((ev: Event) => void) | null = null; + onmessageerror: ((ev: Event) => void) | null = null; private readonly log: Logger = log0.sub(WebSocketBroadcastChannel.name); private closed = false; public readonly name: string; readonly url: URL; constructor(name: string, url: URL = new URL(DEFAULT_WEBSOCKET_URL)) { super(); + this.log.sub("constructor")(`name: ${s(name)}`); this.name = name; this.url = url; - this.log.sub("constructor")(`name: ${s(name)}`); + this.addEventListener("message", (e: Event) => this.onmessage?.(e)); + this.addEventListener( + "messageerror", + (e: Event) => this.onmessageerror?.(e), + ); + registerChannel(this); } postMessage(message: string): void {