Skip to content

Truly independent web browser

LibWeb: Don’t refocus the focused area of a page without system focus

sideshowbarker898e40eca1a8
diff --git a/Libraries/LibWeb/HTML/Focus.cpp b/Libraries/LibWeb/HTML/Focus.cpp
index 530be40f4a0..3ddc234c62f 100644
--- a/Libraries/LibWeb/HTML/Focus.cpp
+++ b/Libraries/LibWeb/HTML/Focus.cpp
@@ -89,6 +89,16 @@ static GC::Ptr<Navigable> focus_root(DOM::Document& document)
return navigable->top_level_traversable();
}
+// The currently focused area of root, or without system focus, the area the tab's focused navigable shows: where focus
+// would be with system focus. Starting at the focused navigable means a focused area another process took focus from
+// doesn't count as focused.
+static GC::Ptr<DOM::Node> currently_or_otherwise_focused_area(Navigable& root)
+{
+ if (root.page().client().has_focus())
+ return root.currently_focused_area();
+ return root.focused_area_shown_by_focused_navigable_regardless_of_system_focus();
+}
+
static GC::Ptr<Navigable> navigable_of_focused_area(DOM::Node& focused_area)
{
if (auto* container = as_if<NavigableContainer>(focused_area)) {
@@ -640,8 +650,10 @@ static GC::Ptr<DOM::Node> get_focusable_area(DOM::Node& focus_target, FocusTrigg
return nullptr;
// 1. Let focusedElement be the currently focused area of a top-level traversable's DOM anchor.
+ // AD-HOC: Without system focus, that's null; take the area it would be with system focus instead, so the
+ // shadow host keeps the delegate that has focus (see the focusing steps' step 5).
if (auto root = focus_root(element->document())) {
- if (auto focused_element = root->currently_focused_area()) {
+ if (auto focused_element = currently_or_otherwise_focused_area(*root)) {
// 2. If focus target is a shadow-including inclusive ancestor of focusedElement, then
// return focusedElement.
if (element->is_shadow_including_inclusive_ancestor_of(*focused_element))
@@ -709,7 +721,11 @@ void run_focusing_steps(GC::Ptr<DOM::Node> new_focus_target, GC::Ptr<DOM::Node>
auto root = focus_root(new_focus_target->document());
if (!root)
return;
- if (new_focus_target.ptr() == root->currently_focused_area().ptr()) {
+ // AD-HOC: Without system focus, the currently focused area of the top-level traversable is null, so the spec's
+ // check never matches. Focusing the area that keeps focus then fires the focus events again, and a page
+ // whose focus handler focuses its own target again recurses until the stack runs out. Compare against the
+ // area that would be focused with system focus.
+ if (new_focus_target.ptr() == currently_or_otherwise_focused_area(*root).ptr()) {
// NB: focus()'s focusVisible option still applies to the element that already has focus, e.g. the delegate a
// shadow host resolved to.
if (focus_visible.has_value())
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index 41882d454be..4b877d714b6 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -6105,7 +6105,16 @@ void LocalNavigable::inform_the_navigation_api_about_aborting_navigation()
GC::Ptr<DOM::Node> LocalNavigable::currently_focused_area()
{
// 1. If traversable does not have system focus, then return null.
- if (!is_focused())
+ if (!page().client().has_focus())
+ return nullptr;
+ return focused_area_regardless_of_system_focus();
+}
+
+// The rest of the currently focused area's steps, which don't depend on system focus.
+GC::Ptr<DOM::Node> LocalNavigable::focused_area_regardless_of_system_focus()
+{
+ // NB: Below a top-level traversable, focus is here only while this is the tab's focused navigable.
+ if (!is_top_level_traversable() && page().focused_navigable().ptr() != this)
return nullptr;
// 2. Let candidate be traversable's active document.
@@ -6123,7 +6132,7 @@ GC::Ptr<DOM::Node> LocalNavigable::currently_focused_area()
// NB: The active document of a navigable another process hosts is there. The walk goes on from it as the tab's
// focused navigable shows, and the container is as far as focus is seen here otherwise.
if (!is<LocalNavigable>(*content_navigable)) {
- if (auto focused_area = content_navigable->currently_focused_area_shown_by_focused_navigable())
+ if (auto focused_area = content_navigable->focused_area_shown_by_focused_navigable_regardless_of_system_focus())
return focused_area;
return container;
}
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.h b/Libraries/LibWeb/HTML/LocalNavigable.h
index ae45577827a..9896b0e1686 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.h
+++ b/Libraries/LibWeb/HTML/LocalNavigable.h
@@ -170,6 +170,8 @@ public:
[[nodiscard]] bool is_focused() const;
[[nodiscard]] virtual GC::Ptr<DOM::Node> currently_focused_area() override;
+ // What currently_focused_area() would be with system focus.
+ [[nodiscard]] GC::Ptr<DOM::Node> focused_area_regardless_of_system_focus();
struct ChosenNavigable {
GC::Ptr<Navigable> navigable;
diff --git a/Libraries/LibWeb/HTML/Navigable.cpp b/Libraries/LibWeb/HTML/Navigable.cpp
index 48a4fd20639..fb09ba493ac 100644
--- a/Libraries/LibWeb/HTML/Navigable.cpp
+++ b/Libraries/LibWeb/HTML/Navigable.cpp
@@ -82,14 +82,18 @@ GC::Ptr<DOM::Node> Navigable::currently_focused_area_shown_by_focused_navigable(
{
if (!page().client().has_focus())
return nullptr;
+ return focused_area_shown_by_focused_navigable_regardless_of_system_focus();
+}
+GC::Ptr<DOM::Node> Navigable::focused_area_shown_by_focused_navigable_regardless_of_system_focus()
+{
auto focused_navigable = page().focused_navigable();
if (!focused_navigable || (focused_navigable.ptr() != this && !is_ancestor_of(*focused_navigable)))
return nullptr;
for (auto navigable = focused_navigable; navigable; navigable = navigable->parent()) {
if (auto* local_navigable = as_if<LocalNavigable>(*navigable))
- return local_navigable->currently_focused_area();
+ return local_navigable->focused_area_regardless_of_system_focus();
if (navigable.ptr() == this)
return nullptr;
if (auto container = navigable->container())
diff --git a/Libraries/LibWeb/HTML/Navigable.h b/Libraries/LibWeb/HTML/Navigable.h
index 59a7fde8613..48d61f78150 100644
--- a/Libraries/LibWeb/HTML/Navigable.h
+++ b/Libraries/LibWeb/HTML/Navigable.h
@@ -104,6 +104,7 @@ public:
// https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-traversable
virtual GC::Ptr<DOM::Node> currently_focused_area() = 0;
GC::Ptr<DOM::Node> currently_focused_area_shown_by_focused_navigable();
+ GC::Ptr<DOM::Node> focused_area_shown_by_focused_navigable_regardless_of_system_focus();
WebIDL::ExceptionOr<void> navigate(NavigateParams);
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index b185ac8dd9e..1c86cf1b1e1 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -249,6 +249,7 @@ if (NOT WIN32)
TestCrashReportSubmission.cpp
TestFavicon.cpp
TestFileDownloader.cpp
+ TestFocusWithoutSystemFocus.cpp
TestGamepadExposure.cpp
TestImageDecoderIsolation.cpp
TestInputMethodState.cpp
diff --git a/Tests/LibWebView/TestFocusWithoutSystemFocus.cpp b/Tests/LibWebView/TestFocusWithoutSystemFocus.cpp
new file mode 100644
index 00000000000..fd0f8eec292
--- /dev/null
+++ b/Tests/LibWebView/TestFocusWithoutSystemFocus.cpp
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "HeadlessTest.h"
+#include <AK/LexicalPath.h>
+#include <AK/Utf16String.h>
+#include <LibCore/EventLoop.h>
+#include <LibGfx/SystemTheme.h>
+#include <LibTest/TestCase.h>
+#include <LibWebView/HeadlessWebView.h>
+#include <LibWebView/Utilities.h>
+
+// Focusing the area that already has focus does nothing, whether or not the page has system focus. A page whose focus
+// handler focuses its own target again must not recurse when the window is in the background.
+TEST_CASE(focus_already_focused_area_without_system_focus)
+{
+ Test::HeadlessTestEnvironment environment { "TestFocusWithoutSystemFocus"sv };
+
+ auto app = TRY_OR_FAIL(environment.create_application());
+
+ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);
+ auto theme = TRY_OR_FAIL(Gfx::load_system_theme(theme_path.string()));
+
+ auto view = WebView::HeadlessWebView::create(move(theme), { 800, 600 });
+
+ size_t loads_finished = 0;
+ view->on_load_finish = [&](auto const&) { ++loads_finished; };
+ Core::EventLoop::current().spin_until([&]() { return loads_finished >= 1; });
+
+ Optional<Utf16String> title;
+ view->on_title_change = [&](Utf16String const& new_title) { title = new_title; };
+
+ // Each focus handler focuses its own target again, at most once more, so a target that fires focus again for a
+ // focus() on itself counts two events.
+ view->load_html(R"html(<!DOCTYPE html>
+<div id="first" tabindex="0">first</div>
+<div id="second" tabindex="0">second</div>
+<iframe id="frame" srcdoc="<div id=inner tabindex=0>inner</div>"></iframe>
+<div id="host"></div>
+<div id="foreground_host"></div>
+<div id="background_host"></div>
+<script>
+ const counts = {};
+ function count_and_refocus(name, target, refocus) {
+ target.addEventListener("focus", () => {
+ counts[name] = (counts[name] ?? 0) + 1;
+ if (counts[name] < 2)
+ refocus();
+ });
+ }
+ const frame = document.getElementById("frame");
+ let frames_loaded = 0;
+ frame.onload = () => {
+ const inner = frame.contentDocument.getElementById("inner");
+ count_and_refocus("inner", inner, () => inner.focus());
+ count_and_refocus("window", frame.contentWindow, () => frame.contentWindow.focus());
+ ++frames_loaded;
+ };
+ // A shadow host that delegates focus, with an iframe in its shadow tree.
+ for (const id of ["foreground_host", "background_host"]) {
+ const root = document.getElementById(id).attachShadow({ mode: "open", delegatesFocus: true });
+ root.innerHTML = "<input id=outer><iframe srcdoc='<input id=deep>'></iframe>";
+ root.querySelector("iframe").onload = () => ++frames_loaded;
+ }
+ function focus_deep_then_host(id) {
+ const host = document.getElementById(id);
+ host.shadowRoot.querySelector("iframe").contentDocument.getElementById("deep").focus();
+ host.focus();
+ const active = host.shadowRoot.activeElement;
+ return active ? active.id || active.localName : "nothing";
+ }
+ const host = document.getElementById("host");
+ host.attachShadow({ mode: "open", delegatesFocus: true }).innerHTML = "<input id=one><input id=two>";
+ function focused_in_host() {
+ return host.shadowRoot.activeElement?.id ?? "nothing";
+ }
+ for (const name of ["first", "second"]) {
+ const target = document.getElementById(name);
+ count_and_refocus(name, target, () => target.focus());
+ }
+ function focus_and_report(focus) {
+ for (const name in counts)
+ delete counts[name];
+ focus();
+ const fired = Object.entries(counts).map(([name, count]) => `${name}:${count}`).sort().join(" ");
+ document.title = `${fired || "none"} ${document.hasFocus()}`;
+ }
+ function report_when_frame_ready() {
+ if (frames_loaded === 3)
+ document.title = "frame ready";
+ else
+ setTimeout(report_when_frame_ready, 10);
+ }
+ report_when_frame_ready();
+</script>)html"sv);
+ Core::EventLoop::current().spin_until([&]() { return title == "frame ready"sv; });
+
+ auto focus_and_report = [&](StringView focus) {
+ title.clear();
+ view->run_javascript(MUST(String::formatted("focus_and_report(() => {})", focus)));
+ Core::EventLoop::current().spin_until([&]() { return title.has_value(); });
+ return title->to_utf8();
+ };
+
+ auto run_and_report = [&](StringView script) {
+ title.clear();
+ view->run_javascript(MUST(String::from_utf8(script)));
+ Core::EventLoop::current().spin_until([&]() { return title.has_value(); });
+ return title->to_utf8();
+ };
+
+ // A shadow host that delegates focus picks the same delegate without system focus as with it, when focus is in an
+ // iframe in its shadow tree.
+ auto foreground_host_delegate = run_and_report("document.title = 'foreground ' + focus_deep_then_host('foreground_host')"sv);
+
+ // With system focus, a target gets focus once, and its handler's focus() does nothing.
+ VERIFY(focus_and_report("first.focus()"sv) == "first:1 true"sv);
+
+ view->set_has_system_focus(false);
+
+ // Without system focus, focusing the target that keeps focus fires nothing.
+ VERIFY(focus_and_report("first.focus()"sv) == "none false"sv);
+
+ // Moving focus to another target fires its focus event once, and its handler's focus() does nothing.
+ VERIFY(focus_and_report("second.focus()"sv) == "second:1 false"sv);
+ VERIFY(focus_and_report("second.focus()"sv) == "none false"sv);
+
+ // The same holds in a same-process iframe, whose window gets focus along with the element.
+ VERIFY(focus_and_report("frame.contentDocument.getElementById('inner').focus()"sv) == "inner:1 window:1 false"sv);
+ VERIFY(focus_and_report("frame.contentDocument.getElementById('inner').focus()"sv) == "none false"sv);
+
+ // And for the iframe's viewport: Moving focus to it fires its window's focus once, and focusing it again fires nothing.
+ VERIFY(focus_and_report("frame.contentWindow.focus()"sv) == "window:1 false"sv);
+ VERIFY(focus_and_report("frame.contentWindow.focus()"sv) == "none false"sv);
+
+ // A shadow host that delegates focus keeps the delegate that has focus.
+ size_t host_step = 0;
+ auto focused_in_host_after = [&](StringView focus) {
+ title.clear();
+ ++host_step;
+ view->run_javascript(MUST(String::formatted("{}; document.title = '{}: ' + focused_in_host()", focus, host_step)));
+ Core::EventLoop::current().spin_until([&]() { return title.has_value(); });
+ return title->to_utf8();
+ };
+ VERIFY(focused_in_host_after("host.shadowRoot.getElementById('two').focus()"sv) == "1: two"sv);
+ VERIFY(focused_in_host_after("host.focus()"sv) == "2: two"sv);
+
+ auto background_host_delegate = run_and_report("document.title = 'background ' + focus_deep_then_host('background_host')"sv);
+ VERIFY(foreground_host_delegate.bytes_as_string_view().substring_view(11) == background_host_delegate.bytes_as_string_view().substring_view(11));
+
+ outln("PASS: Focusing the area that keeps focus fires no focus events without system focus");
+}