Skip to content

Truly independent web browser

LibWebView: Keep a WebUI channel for each page, not each process

sideshowbarkera35c4962c3b2
diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cpp
index 2894a7bac84..81107389deb 100644
--- a/Libraries/LibWebView/WebContentClient.cpp
+++ b/Libraries/LibWebView/WebContentClient.cpp
@@ -454,16 +454,6 @@ void WebContentClient::close_server_if_unused()
m_detached_page_close_timer->start();
}
-void WebContentClient::set_web_ui(RefPtr<WebUI> web_ui)
-{
- m_web_ui = move(web_ui);
-}
-
-void WebContentClient::web_ui_disconnected(Badge<WebUI>)
-{
- m_web_ui.clear();
-}
-
void WebContentClient::destroy_all_compositor_contexts()
{
m_compositor_contexts.clear();
diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.h
index 181fe16e93f..d7c7422e6f9 100644
--- a/Libraries/LibWebView/WebContentClient.h
+++ b/Libraries/LibWebView/WebContentClient.h
@@ -113,9 +113,6 @@ public:
void set_compositor_connection_id(Badge<Application>, i32);
Optional<i32> compositor_connection_id(Badge<Application>) const { return m_compositor_connection_id; }
- void web_ui_disconnected(Badge<WebUI>);
- void set_web_ui(RefPtr<WebUI>);
- RefPtr<WebUI> const& web_ui() const { return m_web_ui; }
virtual void did_misbehave(StringView message_name, StringView reason) override;
static bool renderers_may_access_cookies_like_http();
static bool renderers_may_synthesize_input();
@@ -264,8 +261,6 @@ private:
bool m_audio_capture_permitted { false };
RefPtr<Core::Timer> m_detached_page_close_timer;
- RefPtr<WebUI> m_web_ui;
-
static HashTable<WebContentClient*>& clients();
};
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 884a2fc4fd4..db59a235617 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -644,11 +644,24 @@ void WebContentPage::close()
m_history_recorded_url_for_current_load.clear();
if (m_client)
m_client->update_audio_capture_permission();
+ m_web_ui = nullptr;
auto owed_replies = move(m_owed_replies);
for (auto owed : owed_replies)
owe_reply(owed);
}
+void WebContentPage::set_web_ui(RefPtr<WebUI> web_ui)
+{
+ m_web_ui = move(web_ui);
+}
+
+// A WebUI whose connection closed is dropped, unless the page has another by then.
+void WebContentPage::web_ui_disconnected(Badge<WebUI>, WebUI& web_ui)
+{
+ if (m_web_ui == &web_ui)
+ m_web_ui = nullptr;
+}
+
void WebContentPage::owe_reply(OwedReply owed)
{
if (m_is_open) {
@@ -2361,12 +2374,14 @@ void WebContentPage::did_finish_loading(Web::HTML::CrossProcessId navigable_id,
// The WebUI channel goes to the process the UI process gave the WebUI's document to, never by a URL a process
// reports. A page that loads anything else loses its channel.
if (auto const& web_ui_host = navigable->active_document().web_ui_host(); web_ui_host.has_value() && client().hosted_web_ui() == web_ui_host) {
- if (auto web_ui = WebUI::create(client(), m_id, *web_ui_host); web_ui.is_error())
+ if (auto web_ui = WebUI::create(client(), m_id, *web_ui_host); web_ui.is_error()) {
warnln("Could not create WebUI for {}: {}", committed_url, web_ui.error());
- else
- client().set_web_ui(web_ui.release_value());
- } else if (auto const& web_ui = client().web_ui(); web_ui && web_ui->page_id() == m_id) {
- client().set_web_ui(nullptr);
+ m_web_ui = nullptr;
+ } else {
+ m_web_ui = web_ui.release_value();
+ }
+ } else {
+ m_web_ui = nullptr;
}
auto title = history_title(view().title(), committed_url);
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index c3a17df4c19..898c1e800e4 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -106,6 +106,12 @@ public:
// awaiting a detached close remains open; it still coordinates its own close.
bool is_open() const { return m_is_open; }
+ // The channel to the WebUI this page shows, if it shows one. Each page has its own, so two WebUI pages in one
+ // process each keep theirs.
+ RefPtr<WebUI> const& web_ui() const { return m_web_ui; }
+ void set_web_ui(RefPtr<WebUI>);
+ void web_ui_disconnected(Badge<WebUI>, WebUI&);
+
// Whether a document this page hosts may use the feature. The process hosting the page can act for any of them.
bool hosts_a_document_allowed_to_use(Web::PermissionsPolicy::PolicyControlledFeature) const;
void close();
@@ -376,6 +382,7 @@ private:
Web::PageId m_id;
WeakPtr<CanonicalTraversable> m_traversable;
bool m_is_open { true };
+ RefPtr<WebUI> m_web_ui;
Optional<PresentedBackingStores> m_presented_backing_stores;
bool m_needs_beforeunload_check { true };
bool m_detached_close_pending { false };
diff --git a/Libraries/LibWebView/WebUI.cpp b/Libraries/LibWebView/WebUI.cpp
index b781558f03c..1aa3d88ec2d 100644
--- a/Libraries/LibWebView/WebUI.cpp
+++ b/Libraries/LibWebView/WebUI.cpp
@@ -7,6 +7,7 @@
#include <LibIPC/Transport.h>
#include <LibIPC/TransportHandle.h>
#include <LibWebView/WebContentClient.h>
+#include <LibWebView/WebContentPage.h>
#include <LibWebView/WebUI.h>
#include <LibWebView/WebUI/BookmarksUI.h>
#include <LibWebView/WebUI/DownloadsUI.h>
@@ -95,7 +96,8 @@ WebUI::~WebUI() = default;
void WebUI::die()
{
if (auto client = m_client.strong_ref())
- client->web_ui_disconnected({});
+ if (auto* page = client->page(m_page_id))
+ page->web_ui_disconnected({}, *this);
}
void WebUI::register_interface(StringView name, Interface interface)
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index c65d0e228da..26b40e1b9c2 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -382,6 +382,12 @@ if (BUILD_TESTING AND NOT WIN32)
)
set_tests_properties(TestWebDriverSettingsChanges PROPERTIES TIMEOUT 120)
+ add_test(
+ NAME TestWebDriverWebUIPagesShareAProcess
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-webdriver-web-ui-pages-share-a-process.py $<TARGET_FILE:WebDriver>
+ )
+ set_tests_properties(TestWebDriverWebUIPagesShareAProcess PROPERTIES TIMEOUT 120)
+
add_test(
NAME TestWebDriverSessionHistory
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-webdriver-session-history.py $<TARGET_FILE:WebDriver>
diff --git a/Tests/LibWebView/TestApplicationDestruction.cpp b/Tests/LibWebView/TestApplicationDestruction.cpp
index 10bca342382..ec84f141aae 100644
--- a/Tests/LibWebView/TestApplicationDestruction.cpp
+++ b/Tests/LibWebView/TestApplicationDestruction.cpp
@@ -110,6 +110,22 @@ TEST_CASE(hsts_store_synchronized_on_destruction)
VERIFY(hsts_store->is_known_hsts_host("example.test"_string));
}
+TEST_CASE(closing_a_page_drops_its_web_ui)
+{
+ TestEnvironment environment;
+ auto app = TRY_OR_FAIL(environment.create_application());
+ auto theme = TRY_OR_FAIL(load_test_theme());
+ auto view = WebView::HeadlessWebView::create(theme, { 1000, 700 });
+ auto& page = view->page();
+ auto web_ui = TRY_OR_FAIL(WebView::WebUI::create(page.client(), page.id(), "settings"_string));
+ VERIFY(web_ui);
+ page.set_web_ui(move(web_ui));
+ EXPECT(page.web_ui());
+
+ page.close();
+ EXPECT(!page.web_ui());
+}
+
TEST_CASE(application_destruction_with_pending_web_ui_callbacks)
{
TestEnvironment environment;
@@ -130,12 +146,12 @@ TEST_CASE(application_destruction_with_pending_web_ui_callbacks)
auto web_ui = TRY_OR_FAIL(WebView::WebUI::create(page.client(), page.id(), MUST(String::from_utf8(host))));
VERIFY(web_ui);
web_ui_lifetimes.append({ page.client(), web_ui, retained_by_callback });
- page.client().set_web_ui(move(web_ui));
+ page.set_web_ui(move(web_ui));
if (retained_by_callback) {
// EventReceiver::deferred_invoke() retains its receiver until the callback is run or discarded.
page.client().deferred_invoke([] { });
- page.client().web_ui()->deferred_invoke([] { });
+ page.web_ui()->deferred_invoke([] { });
}
}
}
diff --git a/Tests/LibWebView/test-webdriver-web-ui-pages-share-a-process.py b/Tests/LibWebView/test-webdriver-web-ui-pages-share-a-process.py
new file mode 100644
index 00000000000..7cd083266b0
--- /dev/null
+++ b/Tests/LibWebView/test-webdriver-web-ui-pages-share-a-process.py
@@ -0,0 +1,83 @@
+#!/usr/bin/env python3
+#
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+import argparse
+import runpy
+import subprocess
+import tempfile
+
+from pathlib import Path
+
+helpers = runpy.run_path(str(Path(__file__).with_name("test-webdriver-delete-session.py")))
+
+
+# A tab opened from a WebUI page starts in that page's process, so a second page of the same WebUI there must not take
+# the first page's channel to the UI process.
+def run_test(webdriver_binary):
+ with tempfile.TemporaryDirectory() as directory:
+ port = helpers["unused_port"]()
+ process = subprocess.Popen(
+ [webdriver_binary, "--headless", "-l", "127.0.0.1", "-p", str(port), "--profile-path", directory]
+ )
+ session = None
+ try:
+ helpers["wait_for_port"](port)
+ session = helpers["create_session"](port)
+
+ def command(path, body):
+ status, payload, raw = helpers["request"](port, "POST", f"/session/{session}/{path}", body)
+ assert status == 200, raw
+ return payload["value"]
+
+ def round_trip():
+ return command(
+ "execute/async",
+ {
+ "script": """
+ const done = arguments[0];
+ document.addEventListener('WebUIMessage', function listener(event) {
+ if (event.detail.name !== 'loadSettings') return;
+ document.removeEventListener('WebUIMessage', listener);
+ done(true);
+ });
+ ladybird.sendMessage('loadCurrentSettings');
+ """,
+ "args": [],
+ },
+ )
+
+ command("timeouts", {"script": 5000})
+ command("url", {"url": "about:settings"})
+ assert round_trip()
+ status, payload, raw = helpers["request"](port, "GET", f"/session/{session}/window")
+ assert status == 200, raw
+ first_window = payload["value"]
+
+ second_window = command("window/new", {"type": "tab"})["handle"]
+ command("window", {"handle": second_window})
+ command("url", {"url": "about:settings"})
+ assert round_trip()
+
+ command("window", {"handle": first_window})
+ assert round_trip(), "The first page lost its WebUI channel"
+ print("PASS: two WebUI pages in one process each keep their channel")
+ finally:
+ try:
+ if session is not None:
+ helpers["request"](port, "DELETE", f"/session/{session}")
+ finally:
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("webdriver_binary")
+ run_test(parser.parse_args().webdriver_binary)