Lightpanda: the headless browser designed for AI and automation
worker: BroadcastChannel
Karl Seguin314d34116990
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex fd50909cc..790a52a0a 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -172,7 +172,7 @@ _http_owner: HttpClient.Owner = .{},_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()).+// channels in this frame's origin_broadcast_channels: std.DoublyLinkedList = .{},// List of active MutationObserversdiff --git a/src/browser/Page.zig b/src/browser/Page.zigindex a6fa6749c..f578fcf43 100644--- a/src/browser/Page.zig+++ b/src/browser/Page.zig@@ -54,6 +54,11 @@ session: *Session,// a cached lookup on Frame 2. We picked the latter.dom_version: usize = 0,+// Monotonic creation counter for BroadcastChannels in this Page. A postMessage+// captures the current value so delivery targets only channels that existed+// when it was called+broadcast_sequence: u64 = 0,+// DOM object factory scoped to this Page's documents.factory: Factory,@@ -287,3 +292,33 @@ fn findPopupBy(self: *Page, comptime field: []const u8, id: u32) ?*Frame {}return null;}++// Snapshots the Execution of every same-origin global in this Page — the root+// frame, descendant iframes, popups (and their descendants), and each frame's+// worker scopes — into `arena`.+//+// The returned set is fixed, so a caller may run user JS (which can create or+// tear down frames/workers) while walking it without invalidating the slice.+pub fn executionsForOrigin(self: *Page, arena: Allocator, origin: *js.Origin) ![]*js.Execution {+ var list: std.ArrayList(*js.Execution) = .empty;+ try appendFrameExecutions(&self.frame, origin, arena, &list);+ for (self.popups.items) |popup| {+ try appendFrameExecutions(popup, origin, arena, &list);+ }+ return list.items;+}++fn appendFrameExecutions(frame: *Frame, origin: *js.Origin, arena: Allocator, list: *std.ArrayList(*js.Execution)) !void {+ if (frame.js.origin == origin) {+ try list.append(arena, &frame.js.execution);+ }+ for (frame.workers.items) |worker| {+ const wgs = worker._worker_scope;+ if (wgs.js.origin == origin) {+ try list.append(arena, &wgs.js.execution);+ }+ }+ for (frame.child_frames.items) |child| {+ try appendFrameExecutions(child, origin, arena, list);+ }+}diff --git a/src/browser/js/Execution.zig b/src/browser/js/Execution.zigindex 6b4bd8cdf..b4fbebd8a 100644--- a/src/browser/js/Execution.zig+++ b/src/browser/js/Execution.zig@@ -101,6 +101,20 @@ pub fn makeRequest(self: *const Execution, req: HttpClient.Request) !void {};}+pub fn getBroadcastChannels(self: *const Execution) *std.DoublyLinkedList {+ return switch (self.js.global) {+ inline else => |g| &g._broadcast_channels,+ };+}++// The global's serialized origin (e.g. "https://example.com"), or null for an+// opaque origin.+pub fn origin(self: *const Execution) ?[]const u8 {+ return switch (self.js.global) {+ inline else => |g| g.origin,+ };+}+// HttpClient.Owner of the current global (Frame or WGS). Used by code// that needs to register an in-flight network operation against the// owning scope without caring whether it's a Frame or a Worker — e.g.diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zigindex 826f9cc38..a7be2d1e8 100644--- a/src/browser/js/bridge.zig+++ b/src/browser/js/bridge.zig@@ -1054,6 +1054,7 @@ pub const WorkerJsApis = flattenTypes(&.{@import("../webapi/PerformanceObserver.zig"),@import("../webapi/storage/CookieStore.zig"),@import("../webapi/event/CookieChangeEvent.zig"),+ @import("../webapi/BroadcastChannel.zig"),});// Master list of ALL JS APIs across all contexts.diff --git a/src/browser/tests/broadcast_channel.html b/src/browser/tests/broadcast_channel.htmlindex 73315ba6d..50aa40103 100644--- a/src/browser/tests/broadcast_channel.html+++ b/src/browser/tests/broadcast_channel.html@@ -1,123 +1,117 @@<!DOCTYPE html><body><script src="testing.js"></script>-<script id="basic">++<script id="basic" type=module>{const bc = new BroadcastChannel("my-channel");testing.expectEqual(true, bc !== undefined);testing.expectEqual("my-channel", bc.name);bc.close();}+</script>-// A message is delivered to other channels with the same name, but never to-// the sender itself.-testing.async(async () => {+<!-- A message is delivered to other channels with the same name, but never to+ the sender itself. -->+<script id="deliver_same_name" type=module>+{+ const state = await testing.async();const sender = new BroadcastChannel("room");const receiver = new BroadcastChannel("room");- let received = null;let senderGot = false;-sender.onmessage = () => { senderGot = true; };+ receiver.onmessage = (e) => state.resolve({ data: e.data, origin: e.origin });+ sender.postMessage("hello");- await new Promise((resolve) => {- receiver.onmessage = (e) => {- received = e.data;- resolve();- };- sender.postMessage("hello");+ await state.done((got) => {+ testing.expectEqual("hello", got.data);+ testing.expectEqual(false, senderGot);+ // MessageEvent.origin is the sender's serialized origin.+ testing.expectEqual(location.origin, got.origin);+ sender.close();+ receiver.close();});+}+</script>- 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 () => {+<!-- Channels with different names do not receive each other's messages. -->+<script id="name_isolation" type=module>+{+ const state = await testing.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; };+ a2.onmessage = (e) => state.resolve(e.data);+ a.postMessage("only-for-a");- await new Promise((resolve) => {- a2.onmessage = (e) => {- a2Data = e.data;- resolve();- };- a.postMessage("only-for-a");+ await state.done((a2Data) => {+ testing.expectEqual("only-for-a", a2Data);+ testing.expectEqual(false, bGot);+ a.close();+ b.close();+ a2.close();});+}+</script>- 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 () => {+<!-- addEventListener works and structured (object) payloads survive. -->+<script id="add_event_listener" type=module>+{+ const state = await testing.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);+ receiver.addEventListener("message", (e) => state.resolve(e.data));+ sender.postMessage({ type: "test", value: 42 });- sender.close();- receiver.close();-});+ await state.done((data) => {+ testing.expectEqual("test", data.type);+ testing.expectEqual(42, data.value);+ sender.close();+ receiver.close();+ });+}+</script>-// The message is structured-cloned: receivers get an independent copy, not the-// sender's literal object, and one receiver mutating it does not affect others.-testing.async(async () => {+<!-- The message is structured-cloned: receivers get an independent copy, not the+ sender's literal object, and one receiver mutating it does not affect others. -->+<script id="structured_clone" type=module>+{+ const state = await testing.async();const sender = new BroadcastChannel("clone");const r1 = new BroadcastChannel("clone");const r2 = new BroadcastChannel("clone");const payload = { n: 1 };- let got1 = null;- let got2 = null;-- await new Promise((resolve) => {- let pending = 2;- const done = () => { if (--pending === 0) resolve(); };- r1.onmessage = (e) => { got1 = e.data; got1.n = 999; done(); };- r2.onmessage = (e) => { got2 = e.data; done(); };- sender.postMessage(payload);+ let got1 = null, got2 = null, pending = 2;+ const maybeDone = () => { if (--pending === 0) state.resolve(); };+ r1.onmessage = (e) => { got1 = e.data; got1.n = 999; maybeDone(); };+ r2.onmessage = (e) => { got2 = e.data; maybeDone(); };+ sender.postMessage(payload);++ await state.done(() => {+ // Not the same object the sender posted.+ testing.expectEqual(false, got1 === payload);+ testing.expectEqual(false, got2 === payload);+ // Each receiver got its own independent copy.+ testing.expectEqual(false, got1 === got2);+ // Sender's object is untouched, and r1's mutation didn't leak into r2.+ testing.expectEqual(1, payload.n);+ testing.expectEqual(1, got2.n);+ testing.expectEqual(999, got1.n);+ sender.close();+ r1.close();+ r2.close();});+}+</script>- // Not the same object the sender posted.- testing.expectEqual(false, got1 === payload);- testing.expectEqual(false, got2 === payload);- // Each receiver got its own independent copy.- testing.expectEqual(false, got1 === got2);- // Sender's object is untouched, and r1's mutation didn't leak into r2.- testing.expectEqual(1, payload.n);- testing.expectEqual(1, got2.n);- testing.expectEqual(999, got1.n);-- sender.close();- r1.close();- r2.close();-});--// A value that cannot be structured-cloned throws synchronously (DataCloneError).+<!-- A value that cannot be structured-cloned throws synchronously (DataCloneError). -->+<script id="uncloneable" type=module>{const bc = new BroadcastChannel("uncloneable");let threw = false;@@ -130,10 +124,13 @@ testing.async(async () => {testing.expectEqual(true, threw);bc.close();}+</script>-// After close(), a channel no longer receives messages, and posting on a-// closed channel throws InvalidStateError.-testing.async(async () => {+<!-- After close(), a channel no longer receives messages, and posting on a+ closed channel throws InvalidStateError. -->+<script id="after_close" type=module>+{+ const state = await testing.async();const sender = new BroadcastChannel("closing");const receiver = new BroadcastChannel("closing");const live = new BroadcastChannel("closing");@@ -142,24 +139,196 @@ testing.async(async () => {receiver.onmessage = () => { receiverGot = true; };receiver.close();- await new Promise((resolve) => {- live.onmessage = () => { resolve(); };- sender.postMessage("after-close");+ live.onmessage = () => state.resolve();+ sender.postMessage("after-close");++ await state.done(() => {+ 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>- testing.expectEqual(false, receiverGot);+<!-- A channel created while a message is being delivered must not receive a+ message that was posted before it existed (destinations are fixed at post+ time). c3, created inside c2's handler, only ever sees "done". -->+<script id="create_during_delivery" type=module>+{+ const state = await testing.async();+ const c1 = new BroadcastChannel("create-during");+ const c2 = new BroadcastChannel("create-during");- sender.close();- let threw = false;- try {- sender.postMessage("nope");- } catch (e) {- threw = true;- testing.expectEqual("InvalidStateError", e.name);- }- testing.expectEqual(true, threw);+ let c3got = null;+ c2.onmessage = () => {+ c2.close();+ const c3 = new BroadcastChannel("create-during");+ c3.onmessage = (ev) => { c3got = ev.data; state.resolve(); };+ c1.postMessage("done");+ };+ c1.postMessage("first");+ c2.postMessage("second"); // must NOT reach c3, which doesn't exist yet++ await state.done(() => {+ testing.expectEqual("done", c3got);+ c1.close();+ });+}+</script>++<!--+ Cross-context delivery: a message reaches same-named channels in *other*+ same-origin globals in the page — iframes and dedicated workers — never just+ the sender's own context. A same-origin iframe (about:blank inherits the+ parent origin) and a dedicated worker (inherits its creator's origin) both+ share the page's origin, so delivery crosses the boundary both ways.+-->++<!-- iframe -> page -->+<script id="iframe_to_page" type=module>+{+ const state = await testing.async();+ const bc = new BroadcastChannel("x-i2p");+ bc.onmessage = (e) => state.resolve(e.data);++ const iframe = document.createElement("iframe");+ document.documentElement.appendChild(iframe);+ const doc = iframe.contentDocument;+ doc.write(+ '<!DOCTYPE html><body><script>' ++ 'const c = new BroadcastChannel("x-i2p");' ++ 'setTimeout(() => c.postMessage("hi-from-iframe"), 10);' ++ '<\/script></body>'+ );+ doc.close();++ await state.done((data) => {+ testing.expectEqual("hi-from-iframe", data);+ bc.close();+ });+}+</script>++<!-- page -> iframe -->+<script id="page_to_iframe" type=module>+{+ const state = await testing.async();++ const iframe = document.createElement("iframe");+ document.documentElement.appendChild(iframe);+ const doc = iframe.contentDocument;+ doc.write(+ '<!DOCTYPE html><body><script>' ++ 'const c = new BroadcastChannel("x-p2i");' ++ 'c.onmessage = (e) => { window.__got = e.data; };' ++ '<\/script></body>'+ );+ doc.close();++ // The iframe's channel is registered synchronously by document.close(), so+ // the listener is ready before we post.+ const bc = new BroadcastChannel("x-p2i");+ bc.postMessage("hi-from-page");++ setTimeout(() => state.resolve(), 100);+ await state.done(() => {+ testing.expectEqual("hi-from-page", iframe.contentWindow.__got);+ bc.close();+ });+}+</script>++<!-- worker -> page -->+<script id="worker_to_page" type=module>+{+ const state = await testing.async();+ const bc = new BroadcastChannel("x-w2p");+ bc.onmessage = (e) => state.resolve(e.data);- live.close();-});+ const blob = new Blob([+ 'const c = new BroadcastChannel("x-w2p");' ++ 'setTimeout(() => c.postMessage("hi-from-worker"), 10);'+ ], { type: "text/javascript" });+ new Worker(URL.createObjectURL(blob));++ await state.done((data) => {+ testing.expectEqual("hi-from-worker", data);+ bc.close();+ });+}+</script>++<!-- page -> worker (worker relays receipt back over Worker.postMessage) -->+<script id="page_to_worker" type=module>+{+ const state = await testing.async();+ const bc = new BroadcastChannel("x-p2w");++ const blob = new Blob([+ 'const c = new BroadcastChannel("x-p2w");' ++ 'c.onmessage = (e) => postMessage({ got: e.data });' ++ 'postMessage({ ready: true });'+ ], { type: "text/javascript" });+ const worker = new Worker(URL.createObjectURL(blob));++ // Post only once the worker's channel exists, to avoid a race.+ worker.onmessage = (e) => {+ if (e.data.ready) {+ bc.postMessage("hi-to-worker");+ } else {+ state.resolve(e.data.got);+ }+ };++ await state.done((got) => {+ testing.expectEqual("hi-to-worker", got);+ bc.close();+ });+}+</script>++<!-- name isolation across contexts: a different-named channel in another+ same-origin context does NOT receive, while a same-named one does -->+<script id="name_isolation_across_frames" type=module>+{+ const state = await testing.async();++ const iframe = document.createElement("iframe");+ document.documentElement.appendChild(iframe);+ const doc = iframe.contentDocument;+ doc.write(+ '<!DOCTYPE html><body><script>' ++ 'const other = new BroadcastChannel("x-iso-other");' ++ 'other.onmessage = () => { window.__leaked = true; };' ++ '<\/script></body>'+ );+ doc.close();++ // Same-page control on the matching name proves the post was delivered.+ const sender = new BroadcastChannel("x-iso");+ const control = new BroadcastChannel("x-iso");+ let controlGot = false;+ control.onmessage = () => { controlGot = true; };++ sender.postMessage("only-x-iso");++ setTimeout(() => state.resolve(), 100);+ await state.done(() => {+ testing.expectEqual(true, controlGot);+ testing.expectEqual(undefined, iframe.contentWindow.__leaked);+ sender.close();+ control.close();+ });+}</script></body>diff --git a/src/browser/webapi/BroadcastChannel.zig b/src/browser/webapi/BroadcastChannel.zigindex 5f2eb3bef..3d47524ff 100644--- a/src/browser/webapi/BroadcastChannel.zig+++ b/src/browser/webapi/BroadcastChannel.zig@@ -20,34 +20,38 @@ 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 Execution = js.Execution;const BroadcastChannel = @This();_proto: *EventTarget,-_frame: *Frame,-_name: []const u8,+_exec: *Execution,+_name: lp.String,+_sequence: u64,_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.+// Intrusive node, registered in `frame._broadcast_channels` (or WGS)+// 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{+pub fn init(name: lp.String.Global, exec: *Execution) !*BroadcastChannel {+ const page = exec.page;+ const self = try exec._factory.eventTarget(BroadcastChannel{._proto = undefined,- ._frame = frame,- ._name = try frame.arena.dupe(u8, name),+ ._exec = exec,+ ._name = name.str,+ ._sequence = page.broadcast_sequence,});- frame._broadcast_channels.append(&self._node);+ page.broadcast_sequence += 1;+ exec.getBroadcastChannels().append(&self._node);return self;}@@ -55,32 +59,23 @@ 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 {+pub fn getName(self: *const BroadcastChannel) lp.String {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 {+pub fn postMessage(self: *BroadcastChannel, message: js.Value, exec: *Execution) !void {if (self._closed) {return error.InvalidStateError;}// StructuredSerialize runs synchronously (per spec): clone the message once- // now so an unserializable value throws a DataCloneError to the caller, and- // so the async delivery has a self-owned snapshot to copy from. Each receiver- // gets its own re-clone of this snapshot in `run()` — that gives every- // MessageEvent an independently owned handle (a shared temp would be freed by- // the first receiver's event teardown, leaving the rest reading a dead slot)- // and honours the spec requirement that receivers don't share one object.+ // now so an unserializable value throws a DataCloneError to the caller.const snapshot = blk: {var ls: js.Local.Scope = undefined;- frame.js.localScope(&ls);+ exec.js.localScope(&ls);defer ls.deinit();// Contain any V8 exception raised by a failed serialization so we can@@ -90,20 +85,21 @@ pub fn postMessage(self: *BroadcastChannel, message: js.Value.Temp, frame: *Framtry_catch.init(&ls.local);defer try_catch.deinit();- const cloned = message.local(&ls.local).structuredCloneTo(&ls.local) catch {+ const cloned = message.structuredCloneTo(&ls.local) catch {return error.DataClone;};break :blk try cloned.temp();};errdefer snapshot.release();- const callback = try frame._factory.create(PostMessageCallback{- .frame = frame,+ const callback = try exec._factory.create(PostMessageCallback{+ .exec = exec,.sender = self,.message = snapshot,+ .post_sequence = exec.page.broadcast_sequence,});- try frame.js.scheduler.add(callback, PostMessageCallback.run, 0, .{+ try exec.js.scheduler.add(callback, PostMessageCallback.run, 0, .{.name = "BroadcastChannel.postMessage",.low_priority = false,.finalizer = PostMessageCallback.cancelled,@@ -115,7 +111,7 @@ pub fn close(self: *BroadcastChannel) void {return;}self._closed = true;- self._frame._broadcast_channels.remove(&self._node);+ self._exec.getBroadcastChannels().remove(&self._node);}pub fn getOnMessage(self: *const BroadcastChannel) ?js.Function.Global {@@ -139,7 +135,8 @@ const PostMessageCallback = struct {// A self-owned structured-clone snapshot of the posted message. Re-cloned// (never shared) into each receiver's MessageEvent, then released.message: js.Value.Temp,- frame: *Frame,+ exec: *Execution,+ post_sequence: u64,// Called by the scheduler if the task is dropped before it runs (e.g. page// teardown). `run` and `cancelled` are mutually exclusive, so the snapshot@@ -151,7 +148,7 @@ const PostMessageCallback = struct {}fn deinit(self: *PostMessageCallback) void {- self.frame._factory.destroy(self);+ self.exec._factory.destroy(self);}fn run(ctx: *anyopaque) !?u32 {@@ -161,57 +158,81 @@ const PostMessageCallback = struct {defer self.deinit();defer self.message.release();- const frame = self.frame;const sender = self.sender;-- var ls: js.Local.Scope = undefined;- frame.js.localScope(&ls);- defer ls.deinit();- const snapshot = self.message.local(&ls.local);-- 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 page = self.exec.page;+ const origin = self.exec.js.origin;++ // MessageEvent.origin is the serialization of the sender's origin (same+ // for every receiver); an opaque origin serializes to "null".+ const sender_origin = self.exec.origin() orelse "null";++ // Snapshot every same-origin global up front. Dispatch (below) runs user+ // JS that can create or tear down frames/workers, so we must not hold a+ // live frame-tree walk across it. Per-global channel lists are intrusive+ // (never realloc) and teardown is deferred to the next tick, so walking+ // each channel list live during dispatch is safe.+ const arena = try page.getArena(.tiny, "BroadcastChannel.postMessage");+ defer page.releaseArena(arena);++ for (try page.executionsForOrigin(arena, origin)) |exec| {+ // The MessageEvent and its cloned `data` must live in the receiver's+ // realm, and its listeners are in the receiver's event manager.+ // localScope enters the receiver's v8 context, so both happen there.+ var ls: js.Local.Scope = undefined;+ exec.js.localScope(&ls);+ defer ls.deinit();+ const snapshot = self.message.local(&ls.local);++ var it = exec.getBroadcastChannels().*.first;+ while (it) |node| : (it = node.next) {+ const channel: *BroadcastChannel = @alignCast(@fieldParentPtr("_node", node));++ // Never deliver to the sender, to closed channels, to channels+ // created after this message was posted, or across names.+ if (channel == sender or channel._closed) {+ continue;+ }+ if (channel._sequence >= self.post_sequence) {+ continue;+ }+ if (sender._name.eql(channel._name) == false) {+ continue;+ }++ const target = channel.asEventTarget();+ if (!exec.hasDirectListeners(target, "message", channel._on_message)) {+ continue;+ }++ // Independent clone per receiver, in the receiver's realm. The+ // snapshot is already plain, serializable data, so this cannot+ // raise a DataCloneError. The resulting temp is owned by the+ // MessageEvent, which releases it on teardown — so each receiver+ // frees only its own handle.+ const cloned = snapshot.structuredCloneTo(&ls.local) catch |err| {+ log.err(.dom, "BroadcastChannel.postMessage", .{ .err = err });+ continue;+ };++ const cloned_temp = cloned.temp() catch |err| {+ log.err(.dom, "BroadcastChannel.postMessage", .{ .err = err });+ continue;+ };++ const event = (MessageEvent.initTrusted(comptime .wrap("message"), .{+ .data = .{ .value = cloned_temp },+ .origin = sender_origin,+ .source = null,+ }, exec.page) catch |err| {+ cloned_temp.release();+ log.err(.dom, "BroadcastChannel.postMessage", .{ .err = err });+ continue;+ }).asEvent();++ exec.dispatch(target, event, channel._on_message, .{ .context = "BroadcastChannel message" }) catch |err| {+ log.err(.dom, "BroadcastChannel.postMessage", .{ .err = err });+ };}-- const target = channel.asEventTarget();- if (!frame._event_manager.hasDirectListeners(target, "message", channel._on_message)) {- continue;- }-- // Independent clone per receiver. The snapshot is already plain,- // serializable data, so this cannot raise a DataCloneError. The- // resulting temp is owned by the MessageEvent, which releases it on- // teardown — so each receiver frees only its own handle.- const cloned = snapshot.structuredCloneTo(&ls.local) catch |err| {- log.err(.dom, "BroadcastChannel.postMessage", .{ .err = err });- continue;- };- const cloned_temp = cloned.temp() catch |err| {- log.err(.dom, "BroadcastChannel.postMessage", .{ .err = err });- continue;- };-- const event = (MessageEvent.initTrusted(comptime .wrap("message"), .{- .data = .{ .value = cloned_temp },- .origin = "",- .source = null,- }, frame._page) catch |err| {- cloned_temp.release();- log.err(.dom, "BroadcastChannel.postMessage", .{ .err = err });- continue;- }).asEvent();-- frame._event_manager.dispatchDirect(target, event, channel._on_message, .{ .context = "BroadcastChannel message" }) catch |err| {- log.err(.dom, "BroadcastChannel.postMessage", .{ .err = err });- };}return null;diff --git a/src/browser/webapi/WorkerGlobalScope.zig b/src/browser/webapi/WorkerGlobalScope.zigindex 16495be85..af2337bc9 100644--- a/src/browser/webapi/WorkerGlobalScope.zig+++ b/src/browser/webapi/WorkerGlobalScope.zig@@ -92,6 +92,10 @@ _event_manager: EventManagerBase,// workers don't have <script> tags._script_manager: ScriptManagerBase,+// List of open BroadcastChannels, used to route postMessage between same-named+// channels in this worker's origin+_broadcast_channels: std.DoublyLinkedList = .{},+// These fields represent the "Window"-like component of the WGS_closed: bool = false,_proto: *EventTarget,@@ -160,6 +164,12 @@ pub fn init(worker: *Worker, url: [:0]const u8) !*WorkerGlobalScope {.identity = &self._identity,});+ // A dedicated worker is in the same agent cluster and inherits its creator's+ // origin. Adopt the parent frame's origin (shared *Origin + v8 security+ // token) in place of the context's initial opaque one, so same-origin+ // features like BroadcastChannel can reach across the page/worker boundary.+ try self.js.setOrigin(self.origin);+return self;}