Skip to content

Lightpanda: the headless browser designed for AI and automation

cdp: route keyboard input to the focused element inside an iframe

Navid EMAD37f81922a874
diff --git a/src/browser/frame/user_input.zig b/src/browser/frame/user_input.zig
index d4366ece4..2bde186de 100644
--- a/src/browser/frame/user_input.zig
+++ b/src/browser/frame/user_input.zig
@@ -848,6 +848,19 @@ pub fn focusedElement(frame: *Frame) ?*Element {
return frame.window._document.getActiveElement();
}
+/// The frame keyboard input goes to. Starting from `frame`, descend while the
+/// focused element is an <iframe> with a loaded document: that iframe holds
+/// the focus chain, so its document's focused element is where keys land.
+pub fn focusedFrame(frame: *Frame) *Frame {
+ var current = frame;
+ while (current.document._active_element) |active| {
+ const iframe = active.is(Element.Html.IFrame) orelse break;
+ const window = iframe._window orelse break;
+ current = window._frame;
+ }
+ return current;
+}
+
/// Dispatches a trusted keydown on `target` then, unless cancelled, types
/// `text` (Chrome's WebKeyboardEvent.text; null when the client sends the
/// char as its own event, as chromedp does). Returns whether the keydown was
diff --git a/src/browser/tests/frames/cross_realm_focus.html b/src/browser/tests/frames/cross_realm_focus.html
index acd9f126d..bd379dd3c 100644
--- a/src/browser/tests/frames/cross_realm_focus.html
+++ b/src/browser/tests/frames/cross_realm_focus.html
@@ -5,11 +5,10 @@
<!--
focus()/blur() and the :focus selector act on the element's own document. Parent
-JS focusing an element inside an iframe must update the iframe document's
-activeElement, not the parent's. Open in Firefox to cross-check.
-
-(Firefox additionally sets the *parent* document.activeElement to the <iframe>
-element; we don't model that, so this file deliberately doesn't assert it.)
+JS focusing an element inside an iframe updates the iframe document's
+activeElement, and — the focus chain running through navigable containers —
+the parent's activeElement becomes the <iframe> itself. Open in Firefox or
+Chrome to cross-check.
-->
<iframe id="idf" src="support/cross_realm_focus.html"></iframe>
@@ -23,6 +22,8 @@ element; we don't model that, so this file deliberately doesn't assert it.)
// against that document — not the parent's.
testing.expectEqual(inp, idoc.activeElement);
testing.expectEqual(inp, idoc.querySelector('input:focus'));
+ // ...and the parent's focused area is the iframe holding it.
+ testing.expectEqual(document.getElementById('idf'), document.activeElement);
inp.blur();
// blur() clears it; activeElement falls back to the iframe body.
diff --git a/src/browser/tests/input_focused_frame.html b/src/browser/tests/input_focused_frame.html
new file mode 100644
index 000000000..654bdb733
--- /dev/null
+++ b/src/browser/tests/input_focused_frame.html
@@ -0,0 +1,7 @@
+<!DOCTYPE html>
+<html>
+<body>
+<input id="outer">
+<iframe id="f" srcdoc="<!DOCTYPE html><input id=inner>"></iframe>
+</body>
+</html>
diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zig
index 13469f278..9a6500c30 100644
--- a/src/browser/webapi/Element.zig
+++ b/src/browser/webapi/Element.zig
@@ -1301,7 +1301,7 @@ pub fn focus(self: *Element, frame: *Frame) !void {
const doc = owner.document;
const old_active = doc._active_element;
if (old_active == self) {
- return;
+ return focusContainer(owner);
}
if (self.isFocusable(owner) == false) {
@@ -1334,6 +1334,21 @@ pub fn focus(self: *Element, frame: *Frame) !void {
// Dispatch focusin on new element (bubbles, composed)
const focusin_event = try FocusEvent.initTrusted(comptime .wrap("focusin"), .{ .bubbles = true, .composed = true, .relatedTarget = old_related }, owner);
try owner._event_manager.dispatch(new_target, focusin_event.asEvent());
+
+ focusContainer(owner);
+}
+
+// The focus chain runs through navigable containers: the <iframe> holding a
+// document with a focused element is itself the focused area of its parent
+// document, and so on up. So the parent's activeElement is that <iframe>, and
+// keyboard input routed from the top-level document reaches the element.
+// https://html.spec.whatwg.org/multipage/interaction.html#focus-chain
+fn focusContainer(owner: *Frame) void {
+ const container = owner.iframe orelse return;
+ const parent = owner.parent orelse return;
+ container.asElement().focus(parent) catch |err| {
+ log.debug(.js, "focus container", .{ .err = err });
+ };
}
pub fn blur(self: *Element, frame: *Frame) !void {
diff --git a/src/server/cdp/domains/input.zig b/src/server/cdp/domains/input.zig
index ffa896d23..6a876cf73 100644
--- a/src/server/cdp/domains/input.zig
+++ b/src/server/cdp/domains/input.zig
@@ -57,7 +57,8 @@ fn dispatchKeyEvent(cmd: *CDP.Command) !void {
try cmd.sendResult(null, .{});
const bc = cmd.browser_context orelse return;
- const frame = bc.mainFrame() orelse return;
+ // Keys go to the focused frame, which is an iframe's when one has focus.
+ const frame = Frame.user_input.focusedFrame(bc.mainFrame() orelse return);
// Chrome types text only for an event carrying it: a keyDown with `text`
// (Puppeteer, Playwright) or a `char` (chromedp, after a text-less keyDown).
@@ -158,7 +159,7 @@ fn insertText(cmd: *CDP.Command) !void {
})) orelse return error.InvalidParams;
const bc = cmd.browser_context orelse return;
- const frame = bc.mainFrame() orelse return;
+ const frame = Frame.user_input.focusedFrame(bc.mainFrame() orelse return);
try Frame.user_input.insertText(frame, params.text);
@@ -264,6 +265,50 @@ test "cdp.input: insertText replaces select()ed value of email and number inputs
try testing.expect((try ls.local.compileAndRun("inp.value === 'cd' && inp.selectionStart === 2", null)).isTrue());
}
+test "cdp.input: keyboard input goes to the focused element inside an iframe" {
+ var ctx = try testing.context();
+ defer ctx.deinit();
+
+ const bc = try ctx.loadBrowserContext(.{});
+ const page = try bc.session.createPage();
+ const frame = page.frame().?;
+
+ const url = "http://localhost:9582/src/browser/tests/input_focused_frame.html";
+ try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });
+ try testing.waitForPage(bc);
+
+ var ls: lp.js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+
+ var try_catch: lp.js.TryCatch = undefined;
+ try_catch.init(&ls.local);
+ defer try_catch.deinit();
+
+ _ = try ls.local.compileAndRun("document.getElementById('f').contentDocument.getElementById('inner').focus()", null);
+
+ try ctx.processMessage(.{
+ .id = 1,
+ .method = "Input.insertText",
+ .params = .{ .text = "ab" },
+ });
+ try ctx.processMessage(.{
+ .id = 2,
+ .method = "Input.dispatchKeyEvent",
+ .params = .{ .type = "keyDown", .key = "c", .text = "c" },
+ });
+ try ctx.processMessage(.{
+ .id = 3,
+ .method = "Input.dispatchKeyEvent",
+ .params = .{ .type = "keyUp", .key = "c" },
+ });
+
+ const inner = try ls.local.compileAndRun("document.getElementById('f').contentDocument.getElementById('inner').value", null);
+ try testing.expectEqual("abc", try inner.toStringSlice());
+ const outer = try ls.local.compileAndRun("document.getElementById('outer').value", null);
+ try testing.expectEqual("", try outer.toStringSlice());
+}
+
test "cdp.input: dispatchMouseEvent mouseMoved fires hover events" {
var ctx = try testing.context();
defer ctx.deinit();