Skip to content

Lightpanda: the headless browser designed for AI and automation

reject focus() on non-rendered elements (display:none)

Pierre Tachoire8d1a09317bd0
diff --git a/src/browser/tests/document/focus.html b/src/browser/tests/document/focus.html
index a301d6bfc..6e09469b3 100644
--- a/src/browser/tests/document/focus.html
+++ b/src/browser/tests/document/focus.html
@@ -319,3 +319,38 @@
testing.expectEqual(0, blurCount);
}
</script>
+
+<script id="focus_display_none_noop">
+{
+ // Per HTML spec §6.4.4: an element inside a display:none container
+ // is "not being rendered" and therefore not focusable.
+ const input1 = $('#input1');
+ input1.focus();
+ testing.expectEqual(input1, document.activeElement);
+
+ // Create a hidden container with a button
+ const wrapper = document.createElement('div');
+ wrapper.style.display = 'none';
+ const btn = document.createElement('button');
+ btn.textContent = 'Hidden';
+ wrapper.appendChild(btn);
+ document.body.appendChild(wrapper);
+
+ let focusCount = 0;
+ btn.addEventListener('focus', () => focusCount++);
+
+ // focus() on the hidden button must be a no-op
+ btn.focus();
+ testing.expectEqual(input1, document.activeElement);
+ testing.expectEqual(0, focusCount);
+
+ // Make it visible — now focus should work
+ wrapper.style.display = '';
+ btn.focus();
+ testing.expectEqual(btn, document.activeElement);
+ testing.expectEqual(1, focusCount);
+
+ // Cleanup
+ wrapper.remove();
+}
+</script>
diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zig
index 26ecce962..9c55dffc4 100644
--- a/src/browser/webapi/Element.zig
+++ b/src/browser/webapi/Element.zig
@@ -1024,6 +1024,12 @@ pub fn focus(self: *Element, frame: *Frame) !void {
return;
}
+ // Per HTML spec §6.4.4, an element must be "being rendered" (not
+ // display:none on self or any ancestor) to be focusable.
+ if (!self.checkVisibilityCached(null, frame)) {
+ return;
+ }
+
const FocusEvent = @import("event/FocusEvent.zig");
const new_target = self.asEventTarget();