Skip to content

Truly independent web browser

LibWeb+WebContent: Show iframes’ console messages in DevTools

sideshowbarkerbdd66d6b1ece
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 6eed018526e..da5df620cc6 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -7234,6 +7234,8 @@ void Document::make_active()
if (auto title = document->title(); !title.is_empty())
document->page().client().page_did_change_title(title);
}));
+ } else if (current_navigable) {
+ page().client().page_did_change_active_document_in_child_navigable(*this);
}
// 4. Set window's relevant settings object's execution ready flag.
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index f845a57bb87..e306d91f846 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -1172,6 +1172,11 @@ void LocalNavigable::initialize_navigable(NonnullRefPtr<DocumentState> document_
// top-level traversable by the window handle it gets once it is created, so it does that once it has one.
if (WebDriver::BiDi::is_active() && !is_top_level_traversable() && !is_stand_in)
WebDriver::BiDi::document_is_ready_for_scripts(document);
+
+ // A child navigable's first document became active before it had a navigable, so the page client hears of it here,
+ // as it hears of each document that later becomes active in the navigable.
+ if (!is_top_level_traversable() && !is_stand_in)
+ page().client().page_did_change_active_document_in_child_navigable(document);
}
// AD-HOC: The debug settings and the compositor tree are per page, so a child navigable starts from its parent's. A
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index ca854e5e086..f3f022c45bb 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -774,6 +774,7 @@ public:
virtual void page_did_change_picture_in_picture_video_size(Gfx::IntSize) { }
virtual void page_did_change_picture_in_picture_player_controls_visibility(bool) { }
virtual void page_did_change_active_document_in_top_level_browsing_context(Web::DOM::Document&) { }
+ virtual void page_did_change_active_document_in_child_navigable(Web::DOM::Document&) { }
virtual void page_did_finish_loading(HTML::CrossProcessId, HTML::CrossProcessId) { }
virtual Optional<u64> page_did_start_download(HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response)
{
diff --git a/Services/WebContent/DevToolsConsoleClient.cpp b/Services/WebContent/DevToolsConsoleClient.cpp
index ebdc5871e3f..a8838a30e80 100644
--- a/Services/WebContent/DevToolsConsoleClient.cpp
+++ b/Services/WebContent/DevToolsConsoleClient.cpp
@@ -112,6 +112,11 @@ void DevToolsConsoleClient::handle_result(JS::Value result)
m_client->did_execute_js_console_input(m_object_table.serialize_value(result));
}
+bool DevToolsConsoleClient::has_object(u64 object_id) const
+{
+ return m_object_table.contains(object_id) || m_logged_objects.contains(object_id);
+}
+
ErrorOr<WebView::DebuggerObjectProperties> DevToolsConsoleClient::properties_for_object(u64 object_id)
{
auto& settings = Web::HTML::relevant_settings_object(m_console_global_environment_extensions->binding_object());
@@ -161,22 +166,13 @@ void DevToolsConsoleClient::end_group()
void DevToolsConsoleClient::send_console_output(WebView::ConsoleOutput console_output)
{
- m_buffered_output.append(console_output);
+ m_client->buffer_console_output(console_output);
auto is_error = console_output.output.has<WebView::ConsoleError>();
if (is_error ? m_client->devtools_takes_console_errors() : m_client->devtools_takes_console_messages())
m_client->did_output_js_console_message(move(console_output));
}
-void DevToolsConsoleClient::send_buffered_console_output(bool messages, bool errors)
-{
- m_buffered_output.for_each([&](WebView::ConsoleOutput const& console_output) {
- auto is_error = console_output.output.has<WebView::ConsoleError>();
- if (is_error ? errors : messages)
- m_client->did_output_js_console_message(console_output);
- });
-}
-
// 2.3. Printer(logLevel, args[, options]), https://console.spec.whatwg.org/#printer
JS::ThrowCompletionOr<JS::Value> DevToolsConsoleClient::printer(JS::Console::LogLevel log_level, PrinterArguments arguments)
{
@@ -264,7 +260,7 @@ JS::ThrowCompletionOr<JS::Value> DevToolsConsoleClient::printer(JS::Console::Log
for (auto value : argument_values)
printed_arguments.unchecked_append(serialize_value(m_console->realm(), value));
}
- m_buffered_output.append(console_log(is_table ? JS::Console::LogLevel::Log : log_level, printed_arguments));
+ m_client->buffer_console_output(console_log(is_table ? JS::Console::LogLevel::Log : log_level, printed_arguments));
// A DevTools client that takes the messages gets grips for the objects instead, which it may expand.
if (!m_client->devtools_takes_console_messages())
diff --git a/Services/WebContent/DevToolsConsoleClient.h b/Services/WebContent/DevToolsConsoleClient.h
index 40c942ca0bc..179713a5cc9 100644
--- a/Services/WebContent/DevToolsConsoleClient.h
+++ b/Services/WebContent/DevToolsConsoleClient.h
@@ -14,7 +14,6 @@
#include <LibWeb/HTML/Scripting/DevToolsLoggedObjects.h>
#include <LibWeb/HTML/Scripting/DevToolsObjectTable.h>
#include <LibWebCommon/WebView/ConsoleOutput.h>
-#include <LibWebCommon/WebView/ConsoleOutputBuffer.h>
#include <WebContent/Forward.h>
#include <WebContent/WebContentConsoleClient.h>
@@ -29,9 +28,9 @@ public:
static JsonValue serialize_value(JS::Realm&, JS::Value);
virtual ~DevToolsConsoleClient() override;
+ bool has_object(u64 object_id) const;
ErrorOr<WebView::DebuggerObjectProperties> properties_for_object(u64 object_id);
void forget_logged_objects() { m_logged_objects.clear(); }
- void send_buffered_console_output(bool messages, bool errors);
private:
DevToolsConsoleClient(JS::Console&, PageClient&, ConsoleGlobalEnvironmentExtensions&);
@@ -52,9 +51,6 @@ private:
// The objects of the messages that the page logged while a DevTools client was taking them.
Web::HTML::DevToolsLoggedObjects m_logged_objects;
-
- // The latest messages, which a DevTools client gets once it asks, so it sees what the page output before.
- WebView::ConsoleOutputBuffer m_buffered_output;
};
}
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index d38603564e5..55f251c689c 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -1020,26 +1020,39 @@ void PageClient::page_did_request_external_url(URL::URL const& url, URL::Origin
void PageClient::page_did_change_active_document_in_top_level_browsing_context(Web::DOM::Document& document)
{
- auto& realm = document.relevant_settings_object().realm();
-
clear_pending_dom_mutations();
if (m_web_ui && &m_web_ui->document() != &document)
m_web_ui.clear();
- // NB: Only the active document of the top-level browsing context has its console client read, so a document gets
- // one when it becomes that, and the many documents that never do (such as those DOMParser creates) never pay
- // for one.
+ // The output that DevTools gets once it asks belongs to the document that the tab shows.
+ if (m_top_level_document_console_client && document.console_client() != m_top_level_document_console_client)
+ m_console_output_buffer = {};
+
+ if (auto console_client = attach_js_console(document))
+ m_top_level_document_console_client = *console_client;
+}
+
+void PageClient::page_did_change_active_document_in_child_navigable(Web::DOM::Document& document)
+{
+ // An iframe's document logs to the tab's console too.
+ (void)attach_js_console(document);
+}
+
+// NB: Only an active document has its console client read, so a document gets one when it becomes active, and the many
+// documents that never do (such as those DOMParser creates) never incur one.
+GC::Ptr<WebContentConsoleClient> PageClient::attach_js_console(Web::DOM::Document& document)
+{
if (!document.console_client())
initialize_js_console(document);
- if (auto console_client = document.console_client()) {
- auto& web_content_console_client = as<WebContentConsoleClient>(*console_client);
- m_top_level_document_console_client = web_content_console_client;
+ auto console_client = document.console_client();
+ if (!console_client)
+ return {};
- auto console_object = realm.intrinsics().console_object();
- console_object->console().set_client(*console_client);
- }
+ auto& realm = document.relevant_settings_object().realm();
+ realm.intrinsics().console_object()->console().set_client(*console_client);
+ return as<WebContentConsoleClient>(*console_client);
}
void PageClient::page_did_finish_loading(Web::HTML::CrossProcessId navigable_id, Web::HTML::CrossProcessId document_id)
@@ -2422,8 +2435,7 @@ void PageClient::set_has_devtools_client(bool has_devtools_client)
if (!has_devtools_client) {
m_devtools_takes_console_messages = false;
m_devtools_takes_console_errors = false;
- if (m_top_level_document_console_client)
- as<DevToolsConsoleClient>(*m_top_level_document_console_client).forget_logged_objects();
+ for_each_devtools_console_client([](DevToolsConsoleClient& client) { client.forget_logged_objects(); });
}
}
@@ -2436,8 +2448,32 @@ void PageClient::start_sending_console_output(bool messages, bool errors)
m_devtools_takes_console_messages |= messages;
m_devtools_takes_console_errors |= errors;
- if ((new_messages || new_errors) && m_top_level_document_console_client)
- as<DevToolsConsoleClient>(*m_top_level_document_console_client).send_buffered_console_output(new_messages, new_errors);
+ if (!new_messages && !new_errors)
+ return;
+ m_console_output_buffer.for_each([&](WebView::ConsoleOutput const& console_output) {
+ auto is_error = console_output.output.has<WebView::ConsoleError>();
+ if (is_error ? new_errors : new_messages)
+ did_output_js_console_message(console_output);
+ });
+}
+
+void PageClient::buffer_console_output(WebView::ConsoleOutput console_output)
+{
+ m_console_output_buffer.append(move(console_output));
+}
+
+// The console clients of the active documents that the page shows: the top-level one's and its iframes'.
+void PageClient::for_each_devtools_console_client(Function<void(DevToolsConsoleClient&)> const& callback)
+{
+ for (auto& navigable : Web::HTML::all_local_navigables()) {
+ if (&navigable->page() != &page())
+ continue;
+ auto active_document = navigable->active_document();
+ if (!active_document)
+ continue;
+ if (auto* console_client = as_if<DevToolsConsoleClient>(active_document->console_client().ptr()))
+ callback(*console_client);
+ }
}
void PageClient::page_did_finish_network_request(u64 request_id, u64 body_size, Requests::RequestTimingInfo const& timing_info, Optional<Requests::NetworkError> const& network_error)
@@ -2462,11 +2498,18 @@ void PageClient::did_execute_js_console_input(WebView::DebuggerValue const& resu
client().async_did_execute_js_console_input(m_id, result);
}
+// An object of a console result is in the top-level document's console, but a logged one is in the console of whichever
+// document logged it.
ErrorOr<WebView::DebuggerObjectProperties> PageClient::console_object_properties(u64 object_id)
{
- if (!m_top_level_document_console_client)
+ GC::Ptr<DevToolsConsoleClient> console_client;
+ for_each_devtools_console_client([&](DevToolsConsoleClient& client) {
+ if (!console_client && client.has_object(object_id))
+ console_client = client;
+ });
+ if (!console_client)
return Error::from_string_literal("Unable to locate console object");
- return as<DevToolsConsoleClient>(*m_top_level_document_console_client).properties_for_object(object_id);
+ return console_client->properties_for_object(object_id);
}
void PageClient::js_console_input(StringView js_source)
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index f6e9146a08e..8360e6c9ed4 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -33,6 +33,7 @@
#include <LibWebCommon/WebDriver/Capabilities.h>
#include <LibWebCommon/WebDriver/Response.h>
#include <LibWebCommon/WebDriver/UserPrompt.h>
+#include <LibWebCommon/WebView/ConsoleOutputBuffer.h>
#include <LibWebCommon/WebView/Geolocation.h>
#include <LibWebCommon/WebView/Mutation.h>
#include <LibWebCommon/WebView/StorageSetResult.h>
@@ -121,10 +122,13 @@ public:
bool has_devtools_client() const { return m_has_devtools_client; }
virtual bool has_active_devtools_client() const override { return has_devtools_client(); }
void start_sending_console_output(bool messages, bool errors);
+ void buffer_console_output(WebView::ConsoleOutput);
bool devtools_takes_console_messages() const { return m_devtools_takes_console_messages; }
bool devtools_takes_console_errors() const { return m_devtools_takes_console_errors; }
void initialize_js_console(Web::DOM::Document& document);
+ GC::Ptr<WebContentConsoleClient> attach_js_console(Web::DOM::Document&);
+ void for_each_devtools_console_client(Function<void(DevToolsConsoleClient&)> const&);
void js_console_input(StringView js_source);
Optional<Web::HTML::ConsoleInputCompletion> complete_js_console_input(StringView input);
void did_execute_js_console_input(WebView::DebuggerValue const&);
@@ -272,6 +276,7 @@ private:
virtual void page_did_request_image_context_menu(Web::HTML::CrossProcessId local_root_id, Web::CSSPixelPoint, Web::HTML::PreparedNavigationDescriptor, ByteString const& target, unsigned modifiers, Optional<Gfx::Bitmap const*>) override;
virtual void page_did_request_media_context_menu(Web::HTML::CrossProcessId local_root_id, Web::CSSPixelPoint, ByteString const& target, unsigned modifiers, Web::Page::MediaContextMenu const&, Optional<Web::HTML::PreparedNavigationDescriptor>) override;
virtual void page_did_change_active_document_in_top_level_browsing_context(Web::DOM::Document&) override;
+ virtual void page_did_change_active_document_in_child_navigable(Web::DOM::Document&) override;
virtual void page_did_finish_loading(Web::HTML::CrossProcessId, Web::HTML::CrossProcessId) override;
virtual Optional<u64> page_did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response) override;
virtual Optional<u64> page_did_start_download(URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size) override;
@@ -482,6 +487,10 @@ private:
bool m_has_devtools_client { false };
bool m_devtools_takes_console_messages { false };
bool m_devtools_takes_console_errors { false };
+
+ // The latest output of the document that the tab shows and of its iframes, which a DevTools client gets once it
+ // asks, so it sees what the page output before.
+ WebView::ConsoleOutputBuffer m_console_output_buffer;
};
}
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index e3ab7758619..beefe9767ef 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -45,6 +45,11 @@ if (BUILD_TESTING AND NOT WIN32)
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-worker-error-console.py $<TARGET_FILE:ladybird>
)
set_tests_properties(TestWorkerErrorConsole PROPERTIES TIMEOUT 120)
+ add_test(
+ NAME TestIframeConsole
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-iframe-console.py $<TARGET_FILE:ladybird>
+ )
+ set_tests_properties(TestIframeConsole PROPERTIES TIMEOUT 120)
add_test(
NAME TestWindowSizeReachesEveryPage
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-window-size-reaches-every-page.py $<TARGET_FILE:ladybird>
diff --git a/Tests/LibWebView/test-iframe-console.py b/Tests/LibWebView/test-iframe-console.py
new file mode 100755
index 00000000000..a9e14bd41a6
--- /dev/null
+++ b/Tests/LibWebView/test-iframe-console.py
@@ -0,0 +1,119 @@
+#!/usr/bin/env python3
+#
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+import argparse
+import http.server
+import runpy
+import tempfile
+import threading
+
+from pathlib import Path
+
+devtools = runpy.run_path(str(Path(__file__).with_name("test-devtools-client-follows-the-tab.py")))
+PAGE = b"""<!doctype html><title>iframe-console</title>
+<iframe srcdoc="<script>console.log('logged by the iframe at load', { early: 1 }); window.loggedAtLoad = true;</script>"></iframe>
+<iframe id="blank"></iframe>
+"""
+
+
+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.end_headers()
+ self.wfile.write(PAGE)
+
+ def log_message(self, format, *args):
+ pass
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("ladybird_binary")
+ ladybird_binary = parser.parse_args().ladybird_binary
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ url = f"http://127.0.0.1:{server.server_port}/page"
+ try:
+ with tempfile.TemporaryDirectory(prefix="ladybird-iframe-console-") as profile:
+ process, _, client = devtools["launch"](ladybird_binary, profile, url)
+ try:
+ devtools["wait_for_page"](client, url, "iframe-console")
+ watcher = client.watch_frame_targets()
+ messages = []
+ receive = client.receive
+
+ def receive_and_record_messages():
+ packet = receive()
+ if packet.get("type") == "resources-available-array":
+ for resource_type, resources in packet.get("array", []):
+ if resource_type == "console-message":
+ messages.extend(resources)
+ return packet
+
+ def message_logged(text):
+ return next((message for message in messages if message["arguments"][0] == text), None)
+
+ # Keep console resources even if they arrive while evaluation is retried after a target change.
+ client.receive = receive_and_record_messages
+
+ # What the iframe logged before the client watched arrives once it does.
+ devtools["wait_until"](
+ "the page has loaded, and the iframe has logged",
+ lambda: client.evaluate("document.readyState === 'complete' && frames[0].loggedAtLoad === true"),
+ )
+ client.send({"to": watcher, "type": "watchResources", "resourceTypes": ["console-message"]})
+ client.receive_matching(lambda packet: message_logged("logged by the iframe at load") is not None)
+
+ # What the iframe logs afterward arrives as it comes, with objects the client can expand. The server
+ # replaces the frame target when a load finishes, and the old target's object actors go with it; the
+ # root actor answers a request to one of them with unknownActor, so log a fresh object then.
+ def expand_logged_object():
+ for attempt in range(5):
+ text = f"logged by the iframe later ({attempt})"
+ client.evaluate(f"frames[0].console.log('{text}', {{ late: 2 }}); undefined")
+ if message_logged(text) is None:
+ client.receive_matching(lambda packet, text=text: message_logged(text) is not None)
+ logged = message_logged(text)
+ assert logged is not None, messages
+ grip = logged["arguments"][1]
+ assert grip.get("class") == "Object" and "actor" in grip, grip
+
+ actor = grip["actor"]
+ client.send({"to": actor, "type": "prototypeAndProperties"})
+ reply = client.receive_matching(
+ lambda packet, actor=actor: (
+ packet.get("from") == actor
+ or (packet.get("error") == "unknownActor" and f"'{actor}'" in packet.get("message", ""))
+ )
+ )
+ if reply.get("from") == actor:
+ return reply
+ raise AssertionError("The logged object's actor went away five times")
+
+ properties = expand_logged_object()
+ assert "late" in properties.get("ownProperties", {}), properties
+
+ # An iframe that stays on its first document, about:blank, logs to the tab's console too.
+ client.evaluate(
+ "document.getElementById('blank').contentWindow.console.log('logged by about:blank'); 0"
+ )
+ if message_logged("logged by about:blank") is None:
+ client.receive_matching(lambda packet: message_logged("logged by about:blank") is not None)
+ print("PASS: An iframe's console messages reach the tab's console, and its logged objects expand")
+ finally:
+ client.close()
+ devtools["stop"](process)
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+if __name__ == "__main__":
+ main()