Skip to content

Lightpanda: the headless browser designed for AI and automation

implement BroadcastChannel

Pierre Tachoire7c4df8290343
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zig
index 30f2badc3..fd50909cc 100644
--- a/src/browser/Frame.zig
+++ b/src/browser/Frame.zig
@@ -171,6 +171,10 @@ _http_owner: HttpClient.Owner = .{},
// List of active live ranges (for mutation updates per DOM spec)
_live_ranges: std.DoublyLinkedList = .{},
+// List of open BroadcastChannels, used to route postMessage between same-named
+// channels in this frame (registered on construction, removed on close()).
+_broadcast_channels: std.DoublyLinkedList = .{},
+
// List of active MutationObservers
_mutation_observers: std.DoublyLinkedList = .{},
_mutation_delivery_scheduled: bool = false,
diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zig
index 2b5dff32a..826f9cc38 100644
--- a/src/browser/js/bridge.zig
+++ b/src/browser/js/bridge.zig
@@ -935,6 +935,7 @@ pub const PageJsApis = flattenTypes(&.{
@import("../webapi/event/ToggleEvent.zig"),
@import("../webapi/MessageChannel.zig"),
@import("../webapi/MessagePort.zig"),
+ @import("../webapi/BroadcastChannel.zig"),
@import("../webapi/Worker.zig"),
@import("../webapi/media/MediaError.zig"),
@import("../webapi/media/TextTrackCue.zig"),
diff --git a/src/browser/tests/broadcast_channel.html b/src/browser/tests/broadcast_channel.html
new file mode 100644
index 000000000..7f2e77681
--- /dev/null
+++ b/src/browser/tests/broadcast_channel.html
@@ -0,0 +1,117 @@
+<!DOCTYPE html>
+<body>
+<script src="testing.js"></script>
+<script id="basic">
+{
+ const bc = new BroadcastChannel("my-channel");
+ testing.expectEqual(true, bc !== undefined);
+ testing.expectEqual("my-channel", bc.name);
+ bc.close();
+}
+
+// A message is delivered to other channels with the same name, but never to
+// the sender itself.
+testing.async(async () => {
+ const sender = new BroadcastChannel("room");
+ const receiver = new BroadcastChannel("room");
+
+ let received = null;
+ let senderGot = false;
+
+ sender.onmessage = () => { senderGot = true; };
+
+ await new Promise((resolve) => {
+ receiver.onmessage = (e) => {
+ received = e.data;
+ resolve();
+ };
+ sender.postMessage("hello");
+ });
+
+ testing.expectEqual("hello", received);
+ testing.expectEqual(false, senderGot);
+
+ sender.close();
+ receiver.close();
+});
+
+// Channels with different names do not receive each other's messages.
+testing.async(async () => {
+ const a = new BroadcastChannel("chan-a");
+ const b = new BroadcastChannel("chan-b");
+ const a2 = new BroadcastChannel("chan-a");
+
+ let bGot = false;
+ let a2Data = null;
+
+ b.onmessage = () => { bGot = true; };
+
+ await new Promise((resolve) => {
+ a2.onmessage = (e) => {
+ a2Data = e.data;
+ resolve();
+ };
+ a.postMessage("only-for-a");
+ });
+
+ testing.expectEqual("only-for-a", a2Data);
+ testing.expectEqual(false, bGot);
+
+ a.close();
+ b.close();
+ a2.close();
+});
+
+// addEventListener works and structured (object) payloads survive.
+testing.async(async () => {
+ const sender = new BroadcastChannel("objects");
+ const receiver = new BroadcastChannel("objects");
+
+ let data = null;
+ await new Promise((resolve) => {
+ receiver.addEventListener("message", (e) => {
+ data = e.data;
+ resolve();
+ });
+ sender.postMessage({ type: "test", value: 42 });
+ });
+
+ testing.expectEqual("test", data.type);
+ testing.expectEqual(42, data.value);
+
+ sender.close();
+ receiver.close();
+});
+
+// After close(), a channel no longer receives messages, and posting on a
+// closed channel throws InvalidStateError.
+testing.async(async () => {
+ const sender = new BroadcastChannel("closing");
+ const receiver = new BroadcastChannel("closing");
+ const live = new BroadcastChannel("closing");
+
+ let receiverGot = false;
+ receiver.onmessage = () => { receiverGot = true; };
+ receiver.close();
+
+ await new Promise((resolve) => {
+ live.onmessage = () => { resolve(); };
+ sender.postMessage("after-close");
+ });
+
+ testing.expectEqual(false, receiverGot);
+
+ sender.close();
+ let threw = false;
+ try {
+ sender.postMessage("nope");
+ } catch (e) {
+ threw = true;
+ testing.expectEqual("InvalidStateError", e.name);
+ }
+ testing.expectEqual(true, threw);
+
+ live.close();
+});
+</script>
+</body>
diff --git a/src/browser/webapi/BroadcastChannel.zig b/src/browser/webapi/BroadcastChannel.zig
new file mode 100644
index 000000000..beb572727
--- /dev/null
+++ b/src/browser/webapi/BroadcastChannel.zig
@@ -0,0 +1,182 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+const std = @import("std");
+const lp = @import("lightpanda");
+
+const js = @import("../js/js.zig");
+const Frame = @import("../Frame.zig");
+
+const EventTarget = @import("EventTarget.zig");
+const MessageEvent = @import("event/MessageEvent.zig");
+
+const log = lp.log;
+
+const BroadcastChannel = @This();
+
+_proto: *EventTarget,
+_frame: *Frame,
+_name: []const u8,
+_closed: bool = false,
+_on_message: ?js.Function.Global = null,
+_on_message_error: ?js.Function.Global = null,
+
+// Intrusive node, registered in `frame._broadcast_channels` for the lifetime
+// of the channel (until close()). The registry is how a postMessage on one
+// channel finds the other same-named channels to deliver to.
+_node: std.DoublyLinkedList.Node = .{},
+
+pub fn init(name: []const u8, frame: *Frame) !*BroadcastChannel {
+ const self = try frame._factory.eventTarget(BroadcastChannel{
+ ._proto = undefined,
+ ._frame = frame,
+ ._name = try frame.arena.dupe(u8, name),
+ });
+ frame._broadcast_channels.append(&self._node);
+ return self;
+}
+
+pub fn asEventTarget(self: *BroadcastChannel) *EventTarget {
+ return self._proto;
+}
+
+fn fromNode(node: *std.DoublyLinkedList.Node) *BroadcastChannel {
+ return @fieldParentPtr("_node", node);
+}
+
+pub fn getName(self: *const BroadcastChannel) []const u8 {
+ return self._name;
+}
+
+// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-broadcastchannel-postmessage
+// The message is delivered asynchronously to every other BroadcastChannel
+// object with the same name in the same agent cluster, never to the sender.
+pub fn postMessage(self: *BroadcastChannel, message: js.Value.Temp, frame: *Frame) !void {
+ if (self._closed) {
+ return error.InvalidStateError;
+ }
+
+ const callback = try frame._factory.create(PostMessageCallback{
+ .frame = frame,
+ .sender = self,
+ .message = message,
+ });
+
+ try frame.js.scheduler.add(callback, PostMessageCallback.run, 0, .{
+ .name = "BroadcastChannel.postMessage",
+ .low_priority = false,
+ });
+}
+
+pub fn close(self: *BroadcastChannel) void {
+ if (self._closed) {
+ return;
+ }
+ self._closed = true;
+ self._frame._broadcast_channels.remove(&self._node);
+}
+
+pub fn getOnMessage(self: *const BroadcastChannel) ?js.Function.Global {
+ return self._on_message;
+}
+
+pub fn setOnMessage(self: *BroadcastChannel, cb: ?js.Function.Global) !void {
+ self._on_message = cb;
+}
+
+pub fn getOnMessageError(self: *const BroadcastChannel) ?js.Function.Global {
+ return self._on_message_error;
+}
+
+pub fn setOnMessageError(self: *BroadcastChannel, cb: ?js.Function.Global) !void {
+ self._on_message_error = cb;
+}
+
+const PostMessageCallback = struct {
+ sender: *BroadcastChannel,
+ message: js.Value.Temp,
+ frame: *Frame,
+
+ fn deinit(self: *PostMessageCallback) void {
+ self.frame._factory.destroy(self);
+ }
+
+ fn run(ctx: *anyopaque) !?u32 {
+ const self: *PostMessageCallback = @ptrCast(@alignCast(ctx));
+ defer self.deinit();
+ const frame = self.frame;
+ const sender = self.sender;
+
+ var it = frame._broadcast_channels.first;
+ while (it) |node| : (it = node.next) {
+ const channel = BroadcastChannel.fromNode(node);
+
+ // Never deliver to the sender, to closed channels, or across names.
+ if (channel == sender or channel._closed) {
+ continue;
+ }
+ if (!std.mem.eql(u8, channel._name, sender._name)) {
+ continue;
+ }
+
+ const target = channel.asEventTarget();
+ if (!frame._event_manager.hasDirectListeners(target, "message", channel._on_message)) {
+ continue;
+ }
+
+ const event = (MessageEvent.initTrusted(comptime .wrap("message"), .{
+ .data = .{ .value = self.message },
+ .origin = "",
+ .source = null,
+ }, frame._page) catch |err| {
+ log.err(.dom, "BroadcastChannel.postMessage", .{ .err = err });
+ return null;
+ }).asEvent();
+
+ frame._event_manager.dispatchDirect(target, event, channel._on_message, .{ .context = "BroadcastChannel message" }) catch |err| {
+ log.err(.dom, "BroadcastChannel.postMessage", .{ .err = err });
+ };
+ }
+
+ return null;
+ }
+};
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(BroadcastChannel);
+
+ pub const Meta = struct {
+ pub const name = "BroadcastChannel";
+ pub var class_id: bridge.ClassId = undefined;
+ pub const prototype_chain = bridge.prototypeChain();
+ };
+
+ pub const constructor = bridge.constructor(BroadcastChannel.init, .{});
+
+ pub const name = bridge.accessor(BroadcastChannel.getName, null, .{});
+ pub const postMessage = bridge.function(BroadcastChannel.postMessage, .{ .dom_exception = true });
+ pub const close = bridge.function(BroadcastChannel.close, .{});
+
+ pub const onmessage = bridge.accessor(BroadcastChannel.getOnMessage, BroadcastChannel.setOnMessage, .{});
+ pub const onmessageerror = bridge.accessor(BroadcastChannel.getOnMessageError, BroadcastChannel.setOnMessageError, .{});
+};
+
+const testing = @import("../../testing.zig");
+test "WebApi: BroadcastChannel" {
+ try testing.htmlRunner("broadcast_channel.html", .{});
+}
diff --git a/src/browser/webapi/EventTarget.zig b/src/browser/webapi/EventTarget.zig
index d5d073100..cf5238646 100644
--- a/src/browser/webapi/EventTarget.zig
+++ b/src/browser/webapi/EventTarget.zig
@@ -41,6 +41,7 @@ pub const Type = union(enum) {
abort_signal: *@import("AbortSignal.zig"),
media_query_list: *@import("css/MediaQueryList.zig"),
message_port: *@import("MessagePort.zig"),
+ broadcast_channel: *@import("BroadcastChannel.zig"),
text_track_cue: *@import("media/TextTrackCue.zig"),
navigation: *@import("navigation/Navigation.zig"),
screen: *@import("Screen.zig"),
@@ -153,6 +154,7 @@ pub fn format(self: *EventTarget, writer: *std.Io.Writer) !void {
.abort_signal => writer.writeAll("<AbortSignal>"),
.media_query_list => writer.writeAll("<MediaQueryList>"),
.message_port => writer.writeAll("<MessagePort>"),
+ .broadcast_channel => writer.writeAll("<BroadcastChannel>"),
.text_track_cue => writer.writeAll("<TextTrackCue>"),
.navigation => writer.writeAll("<Navigation>"),
.screen => writer.writeAll("<Screen>"),
@@ -177,6 +179,7 @@ pub fn toString(self: *EventTarget) []const u8 {
.abort_signal => return "[object AbortSignal]",
.media_query_list => return "[object MediaQueryList]",
.message_port => return "[object MessagePort]",
+ .broadcast_channel => return "[object BroadcastChannel]",
.text_track_cue => return "[object TextTrackCue]",
.navigation => return "[object Navigation]",
.screen => return "[object Screen]",