Lightpanda: the headless browser designed for AI and automation
events: run a listener in its own world's context
Jay Hemnani8dde9b4007bd
diff --git a/src/browser/EventManagerBase.zig b/src/browser/EventManagerBase.zigindex f42142d75..7f205b2bb 100644--- a/src/browser/EventManagerBase.zig+++ b/src/browser/EventManagerBase.zig@@ -489,6 +489,43 @@ pub const Listener = struct {local: *const js.Local,event: *Event,comptime context: []const u8,+ ) error{ExecutionTerminated}!void {+ // An event caused from an isolated world (e.g. element.focus() called+ // over CDP) must reach a main-world listener with main-world wrappers.+ if (self.function == .handler_source) {+ _ = self.compileHandler(local.ctx, event._current_target.?);+ }+ if (self.otherWorldContext(local)) |ctx| {+ var ls: js.Local.Scope = undefined;+ ctx.localScope(&ls);+ defer ls.deinit();+ return self.invoke(&ls.local, event, context);+ }+ return self.invoke(local, event, context);+ }++ // The context the callback was created in, when it belongs to another+ // world than `local`.+ fn otherWorldContext(self: *const Listener, local: *const js.Local) ?*js.Context {+ const handle: *const js.v8.Object = switch (self.function) {+ .value => |f| @ptrCast(local.toLocal(f).handle),+ .object => |o| local.toLocal(o).handle,+ .handler => |h| @ptrCast(local.toLocal(h orelse return null).handle),+ // compiled by run() before this is called+ .handler_source => unreachable,+ };+ const ctx = js.Context.fromObject(handle) orelse return null;+ if (ctx.identity == local.ctx.identity) {+ return null;+ }+ return ctx;+ }++ fn invoke(+ self: *Listener,+ local: *const js.Local,+ event: *Event,+ comptime context: []const u8,) error{ExecutionTerminated}!void {switch (self.function) {.value => |value| {@@ -560,10 +597,15 @@ pub const Listener = struct {switch (self.function) {.handler => |h| return h,.handler_source => |source| {- // compiled on first use (then turned into a handler).+ // compiled on first use (then turned into a handler), in the+ // main world whichever world asks first.// on error, the handler becomes null.+ const main_ctx = switch (ctx.global) {+ .frame => |frame| frame.main_js,+ .worker => ctx,+ };var ls: js.Local.Scope = undefined;- ctx.localScope(&ls);+ main_ctx.localScope(&ls);defer ls.deinit();var try_catch: js.TryCatch = undefined;diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex ecb722654..87359bb0e 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -266,6 +266,10 @@ charset: []const u8 = "UTF-8",// access to the JavaScript enginejs: *JS.Context,+// The main world's context. `js` is an isolated world's context while that+// world calls into Zig.+main_js: *JS.Context,+// The Page's arena (page.arena), NOT one tied to this Frame. An iframe or// popup that re-navigates is torn down and re-initialized in place while the// Page lives on, and much of what's allocated here must survive.@@ -360,6 +364,7 @@ pub fn init(self: *Frame, frame_id: u32, page: *Page, opts: InitOpts) !void {self.* = .{.js = undefined,+ .main_js = undefined,.page = page,.page_arena = page_arena,.parent = parent,@@ -438,6 +443,7 @@ pub fn init(self: *Frame, frame_id: u32, page: *Page, opts: InitOpts) !void {.local_arena = self.local_arena,});errdefer browser.env.destroyContext(self.js);+ self.main_js = self.js;self.window._performance.attach(self.js);const location = try Location.init("about:blank", self);diff --git a/src/browser/js/Context.zig b/src/browser/js/Context.zigindex c3e4314c2..ba8b1339a 100644--- a/src/browser/js/Context.zig+++ b/src/browser/js/Context.zig@@ -158,6 +158,12 @@ fn fromC(c_context: *const v8.Context) ?*Context {return @ptrCast(@alignCast(v8.v8__Context__GetAlignedPointerFromEmbedderData(c_context, 1)));}+/// The Context an object was created in, or null if that Context is gone.+pub fn fromObject(handle: *const v8.Object) ?*Context {+ const c_context = v8.v8__Object__GetCreationContext(handle) orelse return null;+ return fromC(c_context);+}+/// Returns the Context and v8::Context for the given isolate./// If the current context is from a destroyed Context (e.g., navigated-away iframe),/// falls back to the incumbent context (the calling context).diff --git a/src/server/cdp/domains/page.zig b/src/server/cdp/domains/page.zigindex 621a39bf8..6e0829257 100644--- a/src/server/cdp/domains/page.zig+++ b/src/server/cdp/domains/page.zig@@ -1512,6 +1512,50 @@ test "cdp.frame: isolated world mutation delivers main-world observers" {try ctx.expectSentResult(.{ .result = .{ .type = "string", .value = "a1,b1,c1" } }, .{ .id = 4 });}+// An event caused from an isolated world reaches main-world listeners with+// main-world wrappers: page expandos on the target are visible.+test "cdp.frame: isolated world event reaches main-world listeners with main-world wrappers" {+ var ctx = try testing.context();+ defer ctx.deinit();++ const bc = try ctx.loadBrowserContext(.{ .id = "BID-IW", .url = "hi.html", .target_id = "FID-000000000X".* });+ const root = bc.mainFrame() orelse unreachable;+ const root_id = id.toFrameId(root._frame_id);++ try ctx.processMessage(.{ .id = 1, .method = "Runtime.evaluate", .params = .{+ .expression =+ \\ window.seen = [];+ \\ const el = document.body.appendChild(document.createElement('input'));+ \\ el.marker = 'main';+ \\ const record = (kind) => (e) => seen.push(`${kind} ${e.type} ${e.target === el} ${e.target.marker}`);+ \\ el.addEventListener('focus', record('listener'));+ \\ el.setAttribute('onfocus', "seen.push(`attribute ${event.type} ${event.target === el} ${event.target.marker}`)");+ \\ el.addEventListener('click', { handleEvent: record('object') });+ \\ el.onclick = record('handler');+ ,+ } });++ try ctx.processMessage(.{ .id = 2, .method = "Page.createIsolatedWorld", .params = .{+ .frameId = &root_id,+ .worldName = "utility",+ .grantUniveralAccess = true,+ } });+ const world_ctx = try isolatedWorldContextId(bc, root);++ try ctx.processMessage(.{ .id = 3, .method = "Runtime.evaluate", .params = .{+ .expression = "const i = document.querySelector('input'); i.focus(); i.click();",+ .contextId = world_ctx,+ } });++ try ctx.processMessage(.{ .id = 4, .method = "Runtime.evaluate", .params = .{+ .expression = "seen.join(',')",+ } });+ try ctx.expectSentResult(.{ .result = .{+ .type = "string",+ .value = "listener focus true main,attribute focus true main,object click true main,handler click true main",+ } }, .{ .id = 4 });+}+// Chrome only puts a world in a frame on an explicit trigger. A world the// client asked for on the root must not appear in a sibling frame just// because that frame navigated afterwards.