Truly independent web browser
LibWebView: Give a child frame’s process the tab’s settings
sideshowbarkerbce9ca931910
diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cppindex d919b82f11f..91dea60a763 100644--- a/Libraries/LibWebView/CanonicalNavigable.cpp+++ b/Libraries/LibWebView/CanonicalNavigable.cpp@@ -773,8 +773,8 @@ ErrorOr<NonnullRefPtr<WebContentPage>> CanonicalNavigable::obtain_page_to_host_i}auto& page = *host->page(page_id);- if (traversable.view().has_value())- Application::the().apply_content_blocking_policy(page);+ if (auto view = traversable.view(); view.has_value())+ view->prepare_page_for_navigable(page);return page;}diff --git a/Libraries/LibWebView/HeadlessWebView.cpp b/Libraries/LibWebView/HeadlessWebView.cppindex dfe74fc12b6..8e4b016a024 100644--- a/Libraries/LibWebView/HeadlessWebView.cpp+++ b/Libraries/LibWebView/HeadlessWebView.cpp@@ -268,9 +268,9 @@ void HeadlessWebView::send_system_theme_to_page(WebContentPage& page)page.async_update_system_theme(m_theme);}-void HeadlessWebView::prepare_page_for_tab(WebContentPage& page)+void HeadlessWebView::prepare_page_for_navigable(WebContentPage& page){- ViewImplementation::prepare_page_for_tab(page);+ ViewImplementation::prepare_page_for_navigable(page);page.async_update_screen_rects({ { screen_rect } }, { { screen_rect } }, 0);}diff --git a/Libraries/LibWebView/HeadlessWebView.h b/Libraries/LibWebView/HeadlessWebView.hindex 546ab18336c..9600fd87b5a 100644--- a/Libraries/LibWebView/HeadlessWebView.h+++ b/Libraries/LibWebView/HeadlessWebView.h@@ -61,7 +61,7 @@ protected:HeadlessWebView& adopt_child_web_view(NonnullOwnPtr<HeadlessWebView>);void discard_child_web_view(HeadlessWebView&);void schedule_forced_close();- void prepare_page_for_tab(WebContentPage&) override;+ void prepare_page_for_navigable(WebContentPage&) override;void send_system_theme_to_page(WebContentPage&) override;void update_zoom() override;ViewImplementation* create_view_for_new_tab_or_window(IsPrivate) override;diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cppindex 96f3c8a9846..c2f7806e1ea 100644--- a/Libraries/LibWebView/ViewImplementation.cpp+++ b/Libraries/LibWebView/ViewImplementation.cpp@@ -2859,11 +2859,9 @@ void ViewImplementation::run_webdriver_commands_waiting_for_a_document(Badge<Canrun_webdriver_content_command(command_id, command.navigable_id, command.name, move(command.payload), move(command.arguments));}-void ViewImplementation::prepare_page_for_tab(WebContentPage& page)+void ViewImplementation::prepare_page_for_navigable(WebContentPage& page){- page.async_set_window_handle(m_window_handle);page.async_set_zoom_level(m_zoom_level);- page.async_set_viewport(viewport_size(), m_device_pixel_ratio, m_is_fullscreen);if (m_window_position.has_value())page.async_set_window_position(m_window_position->to_type<Web::DevicePixels>());if (m_window_size.has_value())@@ -2872,7 +2870,6 @@ void ViewImplementation::prepare_page_for_tab(WebContentPage& page)page.async_set_has_focus(traversable().has_system_focus());if (auto focused_navigable_id = traversable().focused_navigable_id(); focused_navigable_id.has_value())page.async_set_focused_navigable(*focused_navigable_id);- Application::the().update_compositor_viewport(page.compositor_context_id(), viewport_size().to_type<int>(), m_device_pixel_ratio);page.async_set_document_cookie_version_buffer(m_document_cookie_version_buffer);if (m_debugger_is_attached)page.async_attach_debugger();@@ -2884,6 +2881,16 @@ void ViewImplementation::prepare_page_for_tab(WebContentPage& page)send_preferences_to_page(page);}+void ViewImplementation::prepare_page_for_tab(WebContentPage& page)+{+ prepare_page_for_navigable(page);+ // The window handle names the tab to WebDriver, and the viewport is the tab's: both belong to the page displaying+ // it, whose traversable is local.+ page.async_set_window_handle(m_window_handle);+ page.async_set_viewport(viewport_size(), m_device_pixel_ratio, m_is_fullscreen);+ Application::the().update_compositor_viewport(page.compositor_context_id(), viewport_size().to_type<int>(), m_device_pixel_ratio);+}+void ViewImplementation::did_change_display_page(Badge<CanonicalNavigable>, RefPtr<WebContentPage> previous_page){display_page_changed(move(previous_page));diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.hindex 44bbc0ea3a0..42d740d62cb 100644--- a/Libraries/LibWebView/ViewImplementation.h+++ b/Libraries/LibWebView/ViewImplementation.h@@ -115,7 +115,11 @@ public:Optional<u64> owner_view_id() const { return m_owner_view_id; }CanonicalTraversable& traversable() const;- virtual void prepare_page_for_tab(WebContentPage&);+ // A page that comes to host any navigable of the tab gets the tab's settings: the spoofed User-Agent and+ // navigator compatibility mode, the preferred languages and color scheme, the window geometry, and the rest of+ // what the UI decides for the tab. A page that displays the tab gets its viewport and focus on top of that.+ virtual void prepare_page_for_navigable(WebContentPage&);+ void prepare_page_for_tab(WebContentPage&);void did_change_display_page(Badge<CanonicalNavigable>, RefPtr<WebContentPage> previous_page);void did_cancel_loading(Badge<CanonicalNavigable>, bool canceled_navigation);void did_stop_loading(Badge<CanonicalTraversable>, bool stopped_navigation);diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex ca9b3227c9a..3f7d1cb011d 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -1082,6 +1082,9 @@ void ConnectionFromClient::debug_request(Web::PageId page_id, ByteString request}if (request == "set-force-dark") {+ // Force dark is the traversable's, which only the page displaying the tab has.+ if (!page->page().has_local_traversable())+ return;bool state = argument == "on";auto traversable = page->page().local_traversable();traversable->set_force_dark_enabled(state);@@ -1091,17 +1094,17 @@ void ConnectionFromClient::debug_request(Web::PageId page_id, ByteString requestreturn;}+ // The debug overlays are drawn by the traversable, which only the page displaying the tab has; a page hosting a+ // child frame of the tab gets the same requests and has nothing to draw them on.if (request == "set-line-box-borders") {- bool state = argument == "on";- auto traversable = page->page().local_traversable();- traversable->set_should_show_line_box_borders(state);+ if (page->page().has_local_traversable())+ page->page().local_traversable()->set_should_show_line_box_borders(argument == "on");return;}if (request == "set-caret-hit-test-debug-overlay") {- bool state = argument == "on";- auto traversable = page->page().local_traversable();- traversable->set_should_show_caret_hit_test_debug_overlay(state);+ if (page->page().has_local_traversable())+ page->page().local_traversable()->set_should_show_caret_hit_test_debug_overlay(argument == "on");return;}diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex d567a20cc8c..f78ff1fe15c 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -304,6 +304,11 @@ if (BUILD_TESTING AND NOT WIN32)COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-window-size-reaches-every-page.py $<TARGET_FILE:ladybird>)set_tests_properties(TestWindowSizeReachesEveryPage PROPERTIES TIMEOUT 120)+ add_test(+ NAME TestUserAgentPresetReachesChildFrames+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-user-agent-preset-reaches-child-frames.py $<TARGET_FILE:ladybird>+ )+ set_tests_properties(TestUserAgentPresetReachesChildFrames PROPERTIES TIMEOUT 120)add_test(NAME TestMessagePortCollectionCOMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-message-port-collection.py $<TARGET_FILE:WebDriver>diff --git a/Tests/LibWebView/test-user-agent-preset-reaches-child-frames.py b/Tests/LibWebView/test-user-agent-preset-reaches-child-frames.pynew file mode 100644index 00000000000..4ec75bc83e4--- /dev/null+++ b/Tests/LibWebView/test-user-agent-preset-reaches-child-frames.py@@ -0,0 +1,139 @@+#!/usr/bin/env python3+#+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++import argparse+import http.server+import json+import runpy+import subprocess+import sys+import tempfile+import threading+import time++from pathlib import Path++devtools = runpy.run_path(str(Path(__file__).with_name("test-devtools-client-follows-the-tab.py")))+DevToolsClient = devtools["DevToolsClient"]+helpers = devtools["helpers"]+stop = devtools["stop"]+wait_until = devtools["wait_until"]+TIMEOUT_SECONDS = helpers["EVENT_TIMEOUT_SECONDS"]++USER_AGENT_PRESET = "Safari macOS Desktop"++# The port the test server listens on, for the child frame's cross-site URL.+server_port = 0+++class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ if self.path == "/favicon.ico":+ self.send_error(404)+ return+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ if self.path == "/child":+ # The child frame reports what its own process answers, and what it sends on the wire.+ body = """<!doctype html><title>/child</title><script>+ parent.postMessage(JSON.stringify({ userAgent: navigator.userAgent, languages: navigator.languages }), "*");+ </script>"""+ else:+ body = f"""<!doctype html><title>/parent</title><script>+ window.child = null;+ addEventListener("message", event => {{ window.child = JSON.parse(event.data); }});+ </script><iframe src="http://localhost:{server_port}/child"></iframe>"""+ self.wfile.write(body.encode())++ def log_message(self, format, *args):+ pass+++def launch(ladybird_binary, profile, url):+ # Like the DevTools tests' launch(), with the User-Agent preset the test is about.+ deadline = time.monotonic() + TIMEOUT_SECONDS+ for _ in range(5):+ if time.monotonic() >= deadline:+ break+ devtools_port = helpers["unused_port"]()+ process = subprocess.Popen(+ [+ ladybird_binary,+ "--headless=manual",+ f"--profile-path={profile}",+ f"--devtools={devtools_port}",+ f"--user-agent-preset={USER_AGENT_PRESET}",+ url,+ ],+ stderr=subprocess.PIPE,+ text=True,+ )+ bind_failed = threading.Event()++ def forward_stderr(stderr=process.stderr, bind_failed=bind_failed):+ assert stderr is not None+ for line in stderr:+ if line.startswith("Unable to launch devtools server"):+ bind_failed.set()+ sys.stderr.write(line)++ threading.Thread(target=forward_stderr, daemon=True).start()++ while not bind_failed.is_set() and process.poll() is None and time.monotonic() < deadline:+ try:+ attempt_deadline = min(deadline, time.monotonic() + 1)+ return process, DevToolsClient(devtools_port, deadline=attempt_deadline)+ except OSError:+ pass+ stop(process)+ raise AssertionError("The DevTools server didn't start")+++def test_user_agent_preset_reaches_child_frames(ladybird_binary, profile, server):+ parent_url = f"http://127.0.0.1:{server.server_port}/parent"+ process, client = launch(ladybird_binary, profile, parent_url)+ try:+ wait_until("the tab shows the parent", lambda: client.tab().get("title") == "/parent")+ client.watch_frame_targets()++ parent = json.loads(+ client.evaluate("JSON.stringify({ userAgent: navigator.userAgent, languages: navigator.languages })")+ )+ assert "Safari" in parent["userAgent"] and "Ladybird" not in parent["userAgent"], parent++ # The child frame is cross-site, so another process hosts it: it has to answer with the same spoofed+ # User-Agent and the same languages as the page that frames it.+ wait_until("the child frame reports", lambda: client.evaluate("window.child !== null"))+ child = json.loads(client.evaluate("JSON.stringify(window.child)"))+ assert child == parent, (child, parent)++ print("PASS: A child frame in another process gets the tab's User-Agent preset and languages")+ finally:+ client.close()+ stop(process)+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("ladybird_binary")+ ladybird_binary = parser.parse_args().ladybird_binary++ global server_port+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server_port = server.server_port+ threading.Thread(target=server.serve_forever, daemon=True).start()+ try:+ with tempfile.TemporaryDirectory() as directory:+ test_user_agent_preset_reaches_child_frames(ladybird_binary, Path(directory) / "profile", server)+ finally:+ server.shutdown()+ server.server_close()+++if __name__ == "__main__":+ main()diff --git a/UI/Qt/WebContentView.cpp b/UI/Qt/WebContentView.cppindex 8a41092b93e..30d90708f05 100644--- a/UI/Qt/WebContentView.cpp+++ b/UI/Qt/WebContentView.cpp@@ -1745,9 +1745,9 @@ void WebContentView::update_screen_rects(WebView::WebContentPage& page)}}-void WebContentView::prepare_page_for_tab(WebView::WebContentPage& page)+void WebContentView::prepare_page_for_navigable(WebView::WebContentPage& page){- ViewImplementation::prepare_page_for_tab(page);+ ViewImplementation::prepare_page_for_navigable(page);update_compositor_display_metadata(page);update_screen_rects(page);diff --git a/UI/Qt/WebContentView.h b/UI/Qt/WebContentView.hindex ee10e1c4e48..e96e89de07e 100644--- a/UI/Qt/WebContentView.h+++ b/UI/Qt/WebContentView.h@@ -168,7 +168,7 @@ signals:private:// ^WebView::ViewImplementation- virtual void prepare_page_for_tab(WebView::WebContentPage&) override;+ virtual void prepare_page_for_navigable(WebView::WebContentPage&) override;virtual void send_system_theme_to_page(WebView::WebContentPage&) override;virtual void update_zoom() override;virtual Web::DevicePixelSize viewport_size() const override;