Skip to content

Truly independent web browser

LibWeb+LibWebView+WebContent+WebDriver: Implement WebDriver BiDi

Andreas Klingb7af3afedda2
diff --git a/Libraries/LibJS/Runtime/Object.cpp b/Libraries/LibJS/Runtime/Object.cpp
index 746aa253b8e..7b02233e7e6 100644
--- a/Libraries/LibJS/Runtime/Object.cpp
+++ b/Libraries/LibJS/Runtime/Object.cpp
@@ -361,6 +361,31 @@ bool Object::is_date() const
return is_of_engine_class_or_subclass(JS_LAYOUT_CLASS_ID_DATE);
}
+bool Object::is_weak_map() const
+{
+ return engine_class_id() == JS_LAYOUT_CLASS_ID_WEAK_MAP;
+}
+
+bool Object::is_weak_set() const
+{
+ return engine_class_id() == JS_LAYOUT_CLASS_ID_WEAK_SET;
+}
+
+bool Object::is_generator() const
+{
+ return engine_class_id() == JS_LAYOUT_CLASS_ID_GENERATOR_OBJECT || engine_class_id() == JS_LAYOUT_CLASS_ID_ASYNC_GENERATOR;
+}
+
+bool Object::is_proxy() const
+{
+ return engine_class_id() == JS_LAYOUT_CLASS_ID_PROXY_OBJECT;
+}
+
+bool Object::is_array_buffer() const
+{
+ return is_of_engine_class_or_subclass(JS_LAYOUT_CLASS_ID_ARRAY_BUFFER);
+}
+
ErrorData* Object::error_data()
{
return reinterpret_cast<ErrorData*>(const_cast<JSErrorData*>(js_error_data_of(object_to_abi(*this))));
diff --git a/Libraries/LibJS/Runtime/Object.h b/Libraries/LibJS/Runtime/Object.h
index f955c35456a..4f8ddd1d667 100644
--- a/Libraries/LibJS/Runtime/Object.h
+++ b/Libraries/LibJS/Runtime/Object.h
@@ -155,6 +155,11 @@ public:
[[nodiscard]] bool is_function() const { return has_engine_object_flag(JS_LAYOUT_OBJECT_FLAG_IS_FUNCTION); }
bool is_date() const;
+ bool is_weak_map() const;
+ bool is_weak_set() const;
+ bool is_generator() const;
+ bool is_proxy() const;
+ bool is_array_buffer() const;
[[nodiscard]] bool is_raw_native_function() const { return has_engine_object_flag(JS_LAYOUT_OBJECT_FLAG_IS_RAW_NATIVE_FUNCTION); }
[[nodiscard]] bool is_direct_getter_function() const { return has_engine_object_flag(JS_LAYOUT_OBJECT_FLAG_IS_DIRECT_GETTER_FUNCTION); }
[[nodiscard]] bool has_global_object_flag() const { return has_engine_object_flag(JS_LAYOUT_OBJECT_FLAG_IS_GLOBAL_OBJECT); }
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 53680fdc877..d4f501c0783 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1034,6 +1034,9 @@ set(SOURCES
WebAudio/StereoPannerNode.cpp
WebAudio/WaveShaperNode.cpp
WebDriver/Actions.cpp
+ WebDriver/BiDi/BiDi.cpp
+ WebDriver/BiDi/RemoteValue.cpp
+ WebDriver/BiDi/Script.cpp
WebDriver/Contexts.cpp
WebDriver/ElementLocationStrategies.cpp
WebDriver/ElementReference.cpp
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index 676284c9e0d..b43452002d5 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -93,6 +93,7 @@
#include <LibWeb/ContentSecurityPolicy/Directives/HTMLIntegration.h>
#include <LibWeb/ContentSecurityPolicy/Policy.h>
#include <LibWeb/ContentSecurityPolicy/PolicyList.h>
+#include <LibWeb/Crypto/Crypto.h>
#include <LibWeb/DOM/AbstractElement.h>
#include <LibWeb/DOM/AccessibilityTreeNode.h>
#include <LibWeb/DOM/AdoptedStyleSheets.h>
@@ -264,6 +265,7 @@
#include <LibWeb/UIEvents/TextEvent.h>
#include <LibWeb/UpgradeInsecureRequests/AbstractOperations.h>
#include <LibWeb/ViewTransition/ViewTransition.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/DOMException.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
@@ -501,6 +503,11 @@ WebIDL::ExceptionOr<GC::Ref<Document>> Document::create_and_initialize(Type type
document->m_permissions_policy = permissions_policy.release_value();
document->m_active_sandboxing_flag_set = navigation_params.final_sandboxing_flag_set;
document->m_navigation_id = navigation_params.id;
+
+ // INTEROP: A document that a reload or a traversal populates has no navigation ID, and other engines give its load
+ // one for WebDriver BiDi.
+ if (!document->m_navigation_id.has_value() && WebDriver::BiDi::is_active())
+ document->m_navigation_id = Utf16String::from_utf8(Crypto::generate_random_uuid());
document->set_load_timing_info(load_timing_info);
document->m_was_created_via_cross_origin_redirects = navigation_params.response->redirect_taint() != Fetch::Infrastructure::RedirectTaint::SameOrigin;
document->m_about_base_url = navigation_params.about_base_url;
@@ -1517,6 +1524,11 @@ WebIDL::ExceptionOr<Document*> Document::open(Optional<Utf16String> const&, Opti
// 18. Update the current document readiness of document to "loading".
update_readiness(HTML::DocumentReadyState::Loading);
+ // INTEROP: The HTML Standard leaves the during-loading navigation ID for WebDriver BiDi null for the contents that
+ // document.open() loads. Other engines report the load of the contents as a navigation of its own.
+ if (WebDriver::BiDi::is_active())
+ m_navigation_id = Utf16String::from_utf8(Crypto::generate_random_uuid());
+
// 19. Return document.
return this;
}
@@ -6446,6 +6458,10 @@ void Document::run_unloading_cleanup_steps()
FileAPI::run_unloading_cleanup_steps(*this);
fully_exit_fullscreen();
PictureInPicture::run_unloading_cleanup_steps(*this);
+
+ // https://w3c.github.io/webdriver-bidi/#event-script-realmDestroyed
+ if (WebDriver::BiDi::is_active())
+ WebDriver::BiDi::unloading_document_cleanup_steps(*this);
}
// https://html.spec.whatwg.org/multipage/document-lifecycle.html#destroy-a-document
@@ -6687,9 +6703,13 @@ void Document::abort()
// 3. If document's during-loading navigation ID for WebDriver BiDi is non-null, then:
if (m_navigation_id.has_value()) {
- // FIXME: 1. Invoke WebDriver BiDi navigation aborted with document's node navigable and a new WebDriver BiDi
- // navigation status whose id is document's during-loading navigation ID for WebDriver BiDi, status
- // is "canceled", and url is document's URL.
+ // 1. Invoke WebDriver BiDi navigation aborted with document's node navigable and a new WebDriver BiDi navigation
+ // status whose id is document's during-loading navigation ID for WebDriver BiDi, status is "canceled", and
+ // url is document's URL.
+ if (WebDriver::BiDi::is_active()) {
+ if (auto navigable = this->navigable())
+ WebDriver::BiDi::navigation_event(*navigable, "browsingContext.navigationAborted"sv, m_navigation_id, url());
+ }
// 2. Set document's during-loading navigation ID for WebDriver BiDi to null.
m_navigation_id = {};
@@ -7929,8 +7949,18 @@ void Document::update_for_history_step_application(NonnullRefPtr<HTML::SessionHi
// 9. If documentIsNew is true, then:
if (document_is_new) {
// FIXME: 1. Assert: document's during-loading navigation ID for WebDriver BiDi is not null.
- // FIXME: 2. Invoke WebDriver BiDi navigation committed with navigable and a new WebDriver BiDi navigation
- // status whose id is document's during-loading navigation ID for WebDriver BiDi, status is "committed", and url is document's URL
+ // 2. Invoke WebDriver BiDi navigation committed with navigable and a new WebDriver BiDi navigation status whose
+ // id is document's during-loading navigation ID for WebDriver BiDi, status is "committed", and url is
+ // document's URL
+ if (WebDriver::BiDi::is_active()) {
+ if (auto navigable = this->navigable()) {
+ WebDriver::BiDi::navigation_event(*navigable, "browsingContext.navigationCommitted"sv, m_navigation_id, url());
+
+ // AD-HOC: WebDriver BiDi creates the document's realm, and runs its preload scripts, once the document is
+ // active in its navigable and before scripts may run for it.
+ WebDriver::BiDi::document_is_ready_for_scripts(*this);
+ }
+ }
// 3. If scrollingBlockedInNewDocument is false, try to scroll to the fragment for document.
if (!scrolling_blocked_in_new_document)
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index afaea8dbf41..ad75c249828 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -1032,6 +1032,10 @@ public:
// https://html.spec.whatwg.org/multipage/dom.html#is-initial-about:blank
bool is_initial_about_blank() const { return m_is_initial_about_blank; }
+
+ // https://html.spec.whatwg.org/multipage/dom.html#concept-document-navigation-id
+ Optional<Utf16String> const& during_loading_navigation_id_for_webdriver_bidi() const { return m_navigation_id; }
+ void set_during_loading_navigation_id_for_webdriver_bidi(Optional<Utf16String> navigation_id) { m_navigation_id = move(navigation_id); }
void set_is_initial_about_blank(bool b) { m_is_initial_about_blank = b; }
bool iframe_load_in_progress() const { return m_iframe_load_in_progress; }
diff --git a/Libraries/LibWeb/HTML/HistoryExecutor.cpp b/Libraries/LibWeb/HTML/HistoryExecutor.cpp
index 7879c75abc6..45364e8babc 100644
--- a/Libraries/LibWeb/HTML/HistoryExecutor.cpp
+++ b/Libraries/LibWeb/HTML/HistoryExecutor.cpp
@@ -341,7 +341,7 @@ void HistoryExecutor::run_ui_changing_navigable_history_job(CrossProcessId opera
operation.changing_navigable_jobs.ensure(navigable_id);
- queue_apply_history_step_task(*navigable, GC::create_function(heap(), [this, operation_id, navigation_type, user_involvement, population = move(population), source_snapshot_params, pending_document, claimed_target_entry = move(claimed_target_entry), navigable, on_complete]() mutable {
+ queue_apply_history_step_task(*navigable, GC::create_function(heap(), [this, operation_id, navigation_type, finalized_navigation_id, user_involvement, population = move(population), source_snapshot_params, pending_document, claimed_target_entry = move(claimed_target_entry), navigable, on_complete]() mutable {
// 1. Let displayedEntry be navigable's active session history entry.
auto displayed_entry = navigable->active_session_history_entry();
@@ -492,7 +492,7 @@ void HistoryExecutor::run_ui_changing_navigable_history_job(CrossProcessId opera
: Optional<URL::Origin> {};
navigable->queue_navigation_and_traversal_task_for_session_history_entry_population(
request.history_entry.url, request.source_snapshot_params.allows_downloading, move(fetch_client_origin),
- request.user_involvement, {}, params.release_value(), request.csp_navigation_type,
+ request.user_involvement, request.navigation_id.is_empty() ? Optional<Utf16String> {} : Optional<Utf16String> { request.navigation_id }, params.release_value(), request.csp_navigation_type,
request.history_entry.document_state.reload_pending ? Bindings::NavigationTimingType::Reload : Bindings::NavigationTimingType::BackForward,
output, GC::create_function(heap(), [navigable, after_document_populated](GC::Ptr<PopulateSessionHistoryEntryDocumentOutput> output) {
queue_apply_history_step_task(*navigable, GC::create_function(navigable->heap(), [after_document_populated, output] {
@@ -546,7 +546,7 @@ void HistoryExecutor::run_ui_changing_navigable_history_job(CrossProcessId opera
.csp_navigation_type = ContentSecurityPolicy::Directives::Directive::NavigationType::Other,
.history_handling = Bindings::NavigationHistoryBehavior::Replace,
.user_involvement = user_involvement,
- .navigation_id = {},
+ .navigation_id = finalized_navigation_id.value_or(Utf16String {}),
};
request.history_entry.document_state.reload_pending = input_reload_pending;
request.history_entry.document_state.reload_bypasses_cache = input_reload_bypasses_cache;
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index e15c31b771d..b5787e6c39e 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -97,6 +97,7 @@
#include <LibWeb/UIEvents/InputEvent.h>
#include <LibWeb/UIEvents/InputTypes.h>
#include <LibWeb/UpgradeInsecureRequests/AbstractOperations.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
#include <LibWeb/WebIDL/Promise.h>
#include <LibWeb/XHR/FormData.h>
#include <LibWebCommon/CSS/SystemColor.h>
@@ -1097,7 +1098,7 @@ Vector<NonnullRefPtr<SessionHistoryEntry>> LocalNavigable::session_history_entri
}
// https://html.spec.whatwg.org/multipage/document-sequences.html#initialize-the-navigable
-void LocalNavigable::initialize_navigable(NonnullRefPtr<DocumentState> document_state, GC::Ptr<Navigable> parent, GC::Ref<DOM::Document> document, VisibilityState system_visibility_state)
+void LocalNavigable::initialize_navigable(NonnullRefPtr<DocumentState> document_state, GC::Ptr<Navigable> parent, GC::Ref<DOM::Document> document, VisibilityState system_visibility_state, bool is_stand_in)
{
set_id(page().client().allocate_navigable_id());
@@ -1126,6 +1127,12 @@ void LocalNavigable::initialize_navigable(NonnullRefPtr<DocumentState> document_
// 6. Set the initial visibility state of documentState's document to navigable's traversable navigable's system visibility state.
document->set_initial_visibility_state(system_visibility_state);
+
+ // AD-HOC: A navigable's first document is active in it from the navigable's initialization, before scripts may run
+ // for it, and WebDriver BiDi creates its realm and runs its preload scripts then. WebDriver BiDi names a
+ // 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);
}
// AD-HOC: The debug settings and the compositor tree are per page, so a child navigable starts from its parent's. A
@@ -2946,7 +2953,7 @@ void LocalNavigable::populate_session_history_entry_document(NavigationPopulatio
source_snapshot_params,
request.target_snapshot_params,
request.user_involvement,
- {},
+ request.navigation_id.is_empty() ? Optional<Utf16String> {} : Optional<Utf16String> { request.navigation_id },
NullOrError {},
request.csp_navigation_type,
navigation_timing_type,
@@ -3047,7 +3054,9 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
// 5. Queue a global task on the navigation and traversal task source, given navigable's active window, to run these steps:
queue_global_task(Task::Source::NavigationAndTraversal, HTML::relevant_global_object(*active_window()), GC::create_function(heap(), [this, url, source_allows_downloading, source_interface_origin, user_involvement, navigation_id, navigation_params, csp_navigation_type, navigation_timing_type, output, completion_steps]() mutable {
// 1. If navigable's ongoing navigation no longer equals navigationId, then run completionSteps and abort these steps.
- if (navigation_id.has_value() && ongoing_navigation() != navigation_id) {
+ // NB: A reload history job keeps the traversal marker while its document is populated.
+ auto is_reload_traversal = navigation_timing_type == Bindings::NavigationTimingType::Reload && ongoing_navigation().has<Traversal>();
+ if (navigation_id.has_value() && ongoing_navigation() != navigation_id && !is_reload_traversal) {
stop_or_resume_response_body_delivery(navigation_params);
if (completion_steps)
completion_steps->function()(nullptr);
@@ -3065,6 +3074,11 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
// external software.
output->document = attempt_to_create_a_non_fetch_scheme_document(navigation_params.get<GC::Ref<NonFetchSchemeNavigationParams>>());
+ // INTEROP: A navigation that loads no document is reported as failed to WebDriver BiDi, which is what other
+ // implementations do, so that the navigation's waiters learn it ended.
+ if (!output->document && WebDriver::BiDi::is_active())
+ WebDriver::BiDi::navigation_event(*this, "browsingContext.navigationFailed"sv, navigation_id, url);
+
// 2. Set saveExtraDocumentState to false.
output->save_extra_document_state = false;
}
@@ -3115,7 +3129,18 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent
},
[](auto const&) { });
- // FIXME: 2. Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is navigationParams's response's URL.
+ // 2. Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is navigationParams's response's URL.
+ if (WebDriver::BiDi::is_active()) {
+ auto response_url = navigation_params.visit(
+ [&](GC::Ref<NavigationParams> const& it) { return it->response->url().value_or(url); },
+ [&](auto const&) { return url; });
+ WebDriver::BiDi::navigation_event(*this, "browsingContext.navigationFailed"sv, navigation_id, response_url);
+ }
+ }
+ // INTEROP: A navigation whose fetch failed is reported as failed to WebDriver BiDi too, which is what other
+ // implementations do.
+ else if (WebDriver::BiDi::is_active()) {
+ WebDriver::BiDi::navigation_event(*this, "browsingContext.navigationFailed"sv, navigation_id, error_url);
}
}
@@ -3504,8 +3529,8 @@ void LocalNavigable::begin_navigation(PreparedNavigation navigation)
// then invoke WebDriver BiDi navigation failed with navigable and a WebDriver BiDi navigation status whose id
// is navigationId, status is "canceled", and url is url, and return.
if (active_document.unload_counter() > 0) {
- // FIXME: invoke WebDriver BiDi navigation failed with navigable and a WebDriver BiDi navigation status whose id
- // is navigationId, status is "canceled", and url is url
+ if (WebDriver::BiDi::is_active())
+ WebDriver::BiDi::navigation_event(*this, "browsingContext.navigationFailed"sv, navigation_id, url);
return;
}
@@ -3567,13 +3592,17 @@ void LocalNavigable::begin_navigation(PreparedNavigation navigation)
// 16. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
auto target_snapshot_params = snapshot_target_snapshot_params(*this);
- // FIXME: 17. Invoke WebDriver BiDi navigation started with navigable and a new WebDriver BiDi navigation status whose id
- // is navigationId, status is "pending", and url is url.
+ // 17. Invoke WebDriver BiDi navigation started with navigable and a new WebDriver BiDi navigation status whose id is
+ // navigationId, status is "pending", and url is url.
+ if (WebDriver::BiDi::is_active())
+ WebDriver::BiDi::navigation_event(*this, "browsingContext.navigationStarted"sv, navigation_id, url);
// 18. If navigable's ongoing navigation is "traversal", then:
if (ongoing_navigation().has<Traversal>()) {
- // FIXME: 1. Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status whose id
+ // 1. Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status whose id
// is navigationId, status is "canceled", and url is url.
+ if (WebDriver::BiDi::is_active())
+ WebDriver::BiDi::navigation_event(*this, "browsingContext.navigationFailed"sv, navigation_id, url);
// 2. Return.
return;
@@ -3933,9 +3962,10 @@ void LocalNavigable::navigate_to_a_fragment(URL::URL const& url, HistoryHandling
// historyHandling, and userInvolvement.
page().history_executor().finalize_same_document_navigation(*this, history_entry, entry_to_replace, history_handling, user_involvement, move(previous_entry_persisted_state));
- // FIXME: Invoke WebDriver BiDi fragment navigated with navigable and a new WebDriver BiDi navigation status whose
- // id is navigationId, url is url, and status is "complete".
- (void)navigation_id;
+ // Invoke WebDriver BiDi fragment navigated with navigable and a new WebDriver BiDi navigation status whose id is
+ // navigationId, url is url, and status is "complete".
+ if (WebDriver::BiDi::is_active())
+ WebDriver::BiDi::navigation_event(*this, "browsingContext.fragmentNavigated"sv, navigation_id, url);
}
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#evaluate-a-javascript:-url
@@ -4414,7 +4444,10 @@ void perform_url_and_history_update_steps(DOM::Document& document, URL::URL new_
// historyHandling, and "none".
navigable->page().history_executor().finalize_same_document_navigation(*navigable, new_entry, entry_to_replace, history_handling, UserNavigationInvolvement::None, move(previous_entry_persisted_state));
- // FIXME: Invoke WebDriver BiDi history updated with navigable.
+ // 2. Invoke WebDriver BiDi history updated with navigable.
+ // NB: The browser process names the navigable and its URL, which is its active document's URL.
+ if (WebDriver::BiDi::is_active())
+ WebDriver::BiDi::navigation_event(*navigable, "browsingContext.historyUpdated"sv, {}, document.url());
}
void LocalNavigable::scroll_offset_did_change()
@@ -4523,7 +4556,7 @@ void LocalNavigable::initialize_stand_in(RemoteNavigable& remote_navigable, Sess
document_state->set_about_base_url(document->about_base_url());
// 8. Initialize the navigable navigable given documentState and parentNavigable.
- initialize_navigable(document_state, remote_navigable.parent(), document, visibility_state);
+ initialize_navigable(document_state, remote_navigable.parent(), document, visibility_state, true);
set_id_for_session_history_reconstruction(remote_navigable.id());
// The WindowProxy scripts hold keeps standing for the document the navigable displays, which another page hosts,
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.h b/Libraries/LibWeb/HTML/LocalNavigable.h
index 528e28727d4..bbf38f2c43d 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.h
+++ b/Libraries/LibWeb/HTML/LocalNavigable.h
@@ -83,7 +83,7 @@ public:
using NullOrError = NavigationParamsNullOrError;
using NavigationParamsVariant = HTML::NavigationParamsVariant;
- void initialize_navigable(NonnullRefPtr<DocumentState> document_state, GC::Ptr<Navigable> parent, GC::Ref<DOM::Document> document, VisibilityState system_visibility_state);
+ void initialize_navigable(NonnullRefPtr<DocumentState> document_state, GC::Ptr<Navigable> parent, GC::Ref<DOM::Document> document, VisibilityState system_visibility_state, bool is_stand_in = false);
void inherit_page_state_from(LocalNavigable const& parent);
void set_id_for_session_history_reconstruction(CrossProcessId id) { set_id(id); }
diff --git a/Libraries/LibWeb/HTML/LocalTraversableNavigable.cpp b/Libraries/LibWeb/HTML/LocalTraversableNavigable.cpp
index 23ee290ef7f..d855e13c0e3 100644
--- a/Libraries/LibWeb/HTML/LocalTraversableNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalTraversableNavigable.cpp
@@ -28,6 +28,7 @@
#include <LibWeb/Layout/Viewport.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
#include <LibWebCommon/HTML/NavigationPopulationRequest.h>
namespace Web::HTML {
@@ -127,6 +128,12 @@ GC::Ref<LocalTraversableNavigable> LocalTraversableNavigable::create_for_new_web
traversable->active_browsing_context()->set_browsing_context_group_id(new_web_view.browsing_context_group_id);
new_web_view.page->set_top_level_traversable(traversable);
traversable->set_window_handle(Utf16String::from_ascii_without_validation(new_web_view.window_handle.bytes()));
+
+ // AD-HOC: WebDriver BiDi creates the realm of the traversable's first document, and runs its preload scripts, once
+ // the traversable is named by its window handle.
+ if (WebDriver::BiDi::is_active())
+ WebDriver::BiDi::document_is_ready_for_scripts(*traversable->active_document());
+
return traversable;
}
diff --git a/Libraries/LibWeb/HTML/NavigableContainer.cpp b/Libraries/LibWeb/HTML/NavigableContainer.cpp
index 33f41a35a3b..fdce96bf817 100644
--- a/Libraries/LibWeb/HTML/NavigableContainer.cpp
+++ b/Libraries/LibWeb/HTML/NavigableContainer.cpp
@@ -34,6 +34,7 @@
#include <LibWeb/Page/Page.h>
#include <LibWeb/Page/RenderingStats.h>
#include <LibWeb/Painting/BoxViews.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
namespace Web::HTML {
@@ -359,6 +360,12 @@ void NavigableContainer::destroy_the_child_navigable()
// and the navigable's own document too when another page hosts it. It then continues the destruction here.
document().page().hold_navigable_being_destroyed({}, *navigable);
document().page().client().page_did_request_child_navigable_unload(navigable->id());
+
+ // 10. Invoke WebDriver BiDi navigable destroyed with navigable.
+ // NB: The browser process holds the navigable tree, whose navigables are removed once their documents are
+ // destroyed. It reports navigable's destruction as the tree is now, and ignores the URL given.
+ if (WebDriver::BiDi::is_active())
+ WebDriver::BiDi::navigation_event(*navigable, "browsingContext.contextDestroyed"sv, {}, document().url());
}
// https://html.spec.whatwg.org/multipage/document-lifecycle.html#unload-a-document-and-its-descendants
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index 35e44ba8c3c..3da99c1e4e9 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -69,6 +69,7 @@
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/SVG/SVGDecodedImageData.h>
#include <LibWeb/SVG/SVGScriptElement.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
#include <LibWebCommon/HTML/BrowsingContext.h>
#include <LibWebCommon/Infra/CharacterTypes.h>
#include <LibWebCommon/Infra/Strings.h>
@@ -915,7 +916,13 @@ void HTMLParserEndState::advance_to_dom_content_loaded_phase()
// FIXME: 4. Enable the client message queue of the ServiceWorkerContainer object whose associated service worker client is the Document object's relevant settings object.
- // FIXME: 5. Invoke WebDriver BiDi DOM content loaded with the Document's browsing context, and a new WebDriver BiDi navigation status whose id is the Document object's during-loading navigation ID for WebDriver BiDi, status is "pending", and url is the Document object's URL.
+ // 5. Invoke WebDriver BiDi DOM content loaded with the Document's browsing context, and a new WebDriver BiDi navigation status whose id is the Document object's during-loading navigation ID for WebDriver BiDi, status is "pending", and url is the Document object's URL.
+ // NB: The browsing context's active document's node navigable is the navigable the steps report on.
+ // NB: The initial about:blank document of a navigable is not loaded by a navigation.
+ if (WebDriver::BiDi::is_active() && !document->is_initial_about_blank()) {
+ if (auto navigable = document->navigable())
+ WebDriver::BiDi::navigation_event(*navigable, "browsingContext.domContentLoaded"sv, document->during_loading_navigation_id_for_webdriver_bidi(), document->url());
+ }
// NB: Only advance the state machine after this task has run, so that anything the DOMContentLoaded event
// handlers did (e.g. starting loads that delay the load event) is visible to the remaining phases. This
@@ -1032,9 +1039,15 @@ void HTMLParserEndState::complete()
}
}
- // FIXME: 6. Invoke WebDriver BiDi load complete with the Document's browsing context, and a new WebDriver BiDi navigation status whose id is the Document object's during-loading navigation ID for WebDriver BiDi, status is "complete", and url is the Document object's URL.
+ // 6. Invoke WebDriver BiDi load complete with the Document's browsing context, and a new WebDriver BiDi navigation status whose id is the Document object's during-loading navigation ID for WebDriver BiDi, status is "complete", and url is the Document object's URL.
+ // NB: The initial about:blank document of a navigable is not loaded by a navigation.
+ if (WebDriver::BiDi::is_active() && !document->is_initial_about_blank()) {
+ if (auto navigable = document->navigable())
+ WebDriver::BiDi::navigation_event(*navigable, "browsingContext.load"sv, document->during_loading_navigation_id_for_webdriver_bidi(), document->url());
+ }
- // FIXME: 7. Set the Document object's during-loading navigation ID for WebDriver BiDi to null.
+ // 7. Set the Document object's during-loading navigation ID for WebDriver BiDi to null.
+ document->set_during_loading_navigation_id_for_webdriver_bidi({});
// 8. Set the Document's load timing info's load event end time to the current high resolution time given window.
document->load_timing_info().load_event_end_time = HighResolutionTime::current_high_resolution_time(relevant_global_object(window));
diff --git a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp
index 57b0f65434d..d968b4b8fea 100644
--- a/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/ExceptionReporter.cpp
@@ -20,6 +20,7 @@
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Page/Page.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
#include <LibWeb/WebIDL/DOMException.h>
namespace Web::HTML {
@@ -152,6 +153,11 @@ void report_an_exception(JS::Object& global, JS::Value exception, Optional<Error
// 7. If notHandled is true, then:
if (not_handled) {
+ // https://w3c.github.io/webdriver-bidi/#event-log-entryAdded
+ // NB: WebDriver BiDi defines error reporting steps for an error that is not handled.
+ if (WebDriver::BiDi::is_active())
+ WebDriver::BiDi::error_reporting_steps(principal_realm_settings_object(realm), exception);
+
// 1. Set errorInfo[error] to null.
error_info.error = JS::js_null();
diff --git a/Libraries/LibWeb/WebDriver/BiDi/BiDi.cpp b/Libraries/LibWeb/WebDriver/BiDi/BiDi.cpp
new file mode 100644
index 00000000000..f8505c9fa0a
--- /dev/null
+++ b/Libraries/LibWeb/WebDriver/BiDi/BiDi.cpp
@@ -0,0 +1,471 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/HashTable.h>
+#include <AK/JsonArray.h>
+#include <AK/StringBuilder.h>
+#include <AK/Time.h>
+#include <LibGC/Function.h>
+#include <LibJS/Console.h>
+#include <LibJS/Runtime/ConsoleObject.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/HTML/LocalNavigable.h>
+#include <LibWeb/HTML/LocalTraversableNavigable.h>
+#include <LibWeb/HTML/Navigable.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Window.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
+#include <LibWeb/WebDriver/BiDi/BindingsGlue.h>
+#include <LibWeb/WebDriver/BiDi/RemoteValue.h>
+#include <LibWeb/WebDriver/BiDi/Script.h>
+
+namespace Web::WebDriver::BiDi {
+
+bool g_is_active { false };
+
+static BiDiSessionState& state()
+{
+ static auto& state = *new BiDiSessionState;
+ return state;
+}
+
+static HashTable<String>& enabled_events()
+{
+ static auto& events = *new HashTable<String>;
+ return events;
+}
+
+static EventSink& event_sink()
+{
+ static auto& sink = *new EventSink;
+ return sink;
+}
+
+static void install_console_clients_for_existing_documents();
+
+// NB: The ids of the realms that are reported as destroyed, whose documents are not destroyed yet.
+static HashTable<String>& destroyed_realm_ids()
+{
+ static auto& ids = *new HashTable<String>;
+ return ids;
+}
+
+void set_session_state(BiDiSessionState session_state)
+{
+ auto was_active = g_is_active;
+
+ enabled_events().clear();
+ for (auto const& event_name : session_state.enabled_events)
+ enabled_events().set(event_name);
+
+ state() = move(session_state);
+ g_is_active = state().is_active;
+
+ // NB: The documents that existed before the session started run the console steps from now on.
+ if (g_is_active && !was_active)
+ install_console_clients_for_existing_documents();
+
+ // NB: The objects the handles of a session that ended name are not kept alive any longer.
+ if (!g_is_active && was_active) {
+ fail_all_pending_evaluations();
+ clear_all_handle_object_maps();
+ destroyed_realm_ids().clear();
+ }
+}
+
+BiDiSessionState const& session_state()
+{
+ return state();
+}
+
+bool is_event_enabled(StringView event_name)
+{
+ return enabled_events().contains(event_name);
+}
+
+void set_event_sink(EventSink sink)
+{
+ event_sink() = move(sink);
+}
+
+// https://w3c.github.io/webdriver-bidi/#type-browsingContext-Browsingcontext
+// For navigables with an associated WebDriver window handle the navigable id must be the same as the window handle.
+String navigable_id(HTML::Navigable const& navigable)
+{
+ if (auto const* traversable = as_if<HTML::LocalTraversableNavigable>(navigable); traversable && !traversable->window_handle().is_empty())
+ return traversable->window_handle().to_utf8();
+
+ // NB: This is how the browser process names a navigable that is not a top-level traversable.
+ return MUST(String::formatted("{}-{}", navigable.id().namespace_id, navigable.id().local_id));
+}
+
+void emit_event(HTML::Navigable const& navigable, String name, JsonValue params)
+{
+ if (event_sink().on_event)
+ event_sink().on_event(navigable, name, move(params));
+}
+
+void navigation_event(HTML::Navigable const& navigable, StringView event_name, Optional<Utf16String> const& navigation_id, URL::URL const& url)
+{
+ if (event_sink().on_navigation_event)
+ event_sink().on_navigation_event(navigable, event_name, navigation_id, url);
+}
+
+// https://w3c.github.io/webdriver-bidi/#event-script-realmCreated
+static void emit_realm_created(DOM::Document& document)
+{
+ if (!is_event_enabled("script.realmCreated"sv))
+ return;
+
+ auto navigable = document.navigable();
+ if (!navigable || navigable->active_document().ptr() != &document)
+ return;
+
+ // 1. Let environment settings be the newly created environment settings object.
+ // 2. Let realm info be the result of get the realm info given environment settings.
+ // 3. If realm info is null, return.
+ auto realm_info = get_the_realm_info(document.relevant_settings_object());
+ if (!realm_info.has_value())
+ return;
+
+ // 4. Let related navigables be the result of get related navigables given environment settings.
+ // 5. Let body be a map matching the script.RealmCreated production, with the params field set to realm info.
+ // 6. For each session in the set of sessions for which an event is enabled given "script.realmCreated" and related
+ // navigables:
+ // 1. Emit an event with session and body.
+ emit_event(*navigable, "script.realmCreated"_string, realm_info.release_value());
+}
+
+void document_is_ready_for_scripts(DOM::Document& document)
+{
+ ensure_console_steps_run_for(document);
+
+ // https://w3c.github.io/webdriver-bidi/#event-script-realmCreated
+ // When any of the set up a window environment settings object, set up a worker environment settings object or set up
+ // a worklet environment settings object algorithms are invoked, immediately prior to returning the settings object:
+ // AD-HOC: The settings object of a window is set up before the window has an associated Document with a navigable,
+ // when getting its realm info returns null. The realm is reported as created once its document is active
+ // in a navigable instead.
+ emit_realm_created(document);
+
+ // https://w3c.github.io/webdriver-bidi/#run-webdriver-bidi-preload-scripts
+ run_webdriver_bidi_preload_scripts(document.relevant_settings_object());
+}
+
+// https://w3c.github.io/webdriver-bidi/#event-script-realmDestroyed
+void unloading_document_cleanup_steps(DOM::Document& document)
+{
+ auto& settings = document.relevant_settings_object();
+
+ // 1. Let related navigables be an empty set.
+ // 2. Append document's navigable to related navigables.
+ auto navigable = document.navigable();
+
+ // 3. For each worklet global scope in document's worklet global scopes:
+ // FIXME: Report the realms of worklets.
+
+ // 4. Let environment settings be the environment settings object whose relevant global object's associated Document
+ // is document.
+ // 5. Let realm be environment settings' realm execution context's Realm component.
+ // 6. Let realm id be the realm id for realm.
+ // 7. Let params be a map matching the script.RealmDestroyedParameters production, with the realm field set to realm
+ // id.
+ // 8. Let body be a map matching the script.RealmDestroyed production, with the params field set to params.
+ // 9. For each session in the set of sessions for which an event is enabled given "script.realmDestroyed" and
+ // related navigables:
+ // 1. Emit an event with session and body.
+ // NB: A document whose unloading destroys it runs the unloading document cleanup steps when it is unloaded and again
+ // when it is destroyed, while its realm is destroyed once.
+ auto id = realm_id(settings);
+ if (destroyed_realm_ids().remove(id))
+ return;
+ destroyed_realm_ids().set(id);
+
+ if (navigable && is_event_enabled("script.realmDestroyed"sv)) {
+ JsonObject params;
+ params.set("realm"sv, move(id));
+ emit_event(*navigable, "script.realmDestroyed"_string, move(params));
+ }
+
+ // NB: The realm is discarded, and the objects its handles name with it.
+ clear_handle_object_map(settings);
+ fail_pending_evaluations(settings);
+}
+
+static StringView method_for_log_level(JS::Console::LogLevel log_level)
+{
+ switch (log_level) {
+ case JS::Console::LogLevel::Assert:
+ return "assert"sv;
+ case JS::Console::LogLevel::Count:
+ return "count"sv;
+ case JS::Console::LogLevel::CountReset:
+ return "countReset"sv;
+ case JS::Console::LogLevel::Debug:
+ return "debug"sv;
+ case JS::Console::LogLevel::Dir:
+ return "dir"sv;
+ case JS::Console::LogLevel::DirXML:
+ return "dirxml"sv;
+ case JS::Console::LogLevel::Error:
+ return "error"sv;
+ case JS::Console::LogLevel::Group:
+ return "group"sv;
+ case JS::Console::LogLevel::GroupCollapsed:
+ return "groupCollapsed"sv;
+ case JS::Console::LogLevel::Info:
+ return "info"sv;
+ case JS::Console::LogLevel::Log:
+ return "log"sv;
+ case JS::Console::LogLevel::TimeEnd:
+ return "timeEnd"sv;
+ case JS::Console::LogLevel::TimeLog:
+ return "timeLog"sv;
+ case JS::Console::LogLevel::Table:
+ return "table"sv;
+ case JS::Console::LogLevel::Trace:
+ return "trace"sv;
+ case JS::Console::LogLevel::Warn:
+ return "warn"sv;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-related-navigables
+static GC::Ptr<HTML::Navigable> related_navigable(HTML::EnvironmentSettingsObject& settings)
+{
+ // 1. Let related navigables be an empty set.
+ // 2. If settings' relevant global object is a Window:
+ // 1. Let navigable be relevant global object's associated Document's node navigable.
+ // 2. If navigable is not null, append navigable to related navigables.
+ // FIXME: 3. Otherwise if the global object specified by settings is a WorkerGlobalScope, for each owner in the global
+ // object's owner set:
+ if (auto* window = HTML::window_from_global_object(settings.global_object()))
+ return window->associated_document().navigable();
+
+ // 4. Return related navigables.
+ return nullptr;
+}
+
+// https://w3c.github.io/webdriver-bidi/#event-log-entryAdded
+void console_steps(HTML::EnvironmentSettingsObject& settings, JS::Console::LogLevel log_level, JS::ConsoleClient::PrinterArguments const& arguments)
+{
+ if (!is_active())
+ return;
+
+ auto navigable = related_navigable(settings);
+ if (!navigable)
+ return;
+
+ auto& vm = settings.global_object().vm();
+ auto method = method_for_log_level(log_level);
+
+ // NB: The console groups and traces give their label, which the console formatted from the arguments.
+ GC::RootVector<JS::Value> args;
+ Optional<JsonObject> trace_stack;
+ arguments.visit(
+ [&](JS::Console::Group const& group) {
+ args.append(JS::PrimitiveString::create(vm, group.label));
+ },
+ [&](JS::Console::Trace const& trace) {
+ if (!trace.label.is_empty())
+ args.append(JS::PrimitiveString::create(vm, trace.label));
+
+ JsonArray call_frames;
+ for (auto const& frame : trace.stack) {
+ if (!frame.source_file.has_value())
+ continue;
+ JsonObject frame_info;
+ frame_info.set("columnNumber"sv, frame.column.has_value() && *frame.column > 0 ? *frame.column - 1 : 0);
+ frame_info.set("functionName"sv, frame.function_name.to_utf8());
+ frame_info.set("lineNumber"sv, frame.line.has_value() && *frame.line > 0 ? *frame.line - 1 : 0);
+ frame_info.set("url"sv, frame.source_file->to_utf8());
+ call_frames.must_append(move(frame_info));
+ }
+ JsonObject stack;
+ stack.set("callFrames"sv, move(call_frames));
+ trace_stack = move(stack);
+ },
+ [&](GC::RootVector<JS::Value> const& values) {
+ for (auto value : values)
+ args.append(value);
+ });
+
+ // 1. For each session in active BiDi sessions:
+
+ // 1. If method is "error" or "assert", let level be "error". If method is "debug" or "trace" let level be "debug". If
+ // method is "warn", let level be "warn". Otherwise let level be "info".
+ auto level = "info"sv;
+ if (method.is_one_of("error"sv, "assert"sv))
+ level = "error"sv;
+ else if (method.is_one_of("debug"sv, "trace"sv))
+ level = "debug"sv;
+ else if (method == "warn"sv)
+ level = "warn"sv;
+
+ // 2. Let timestamp be a time value representing the current date and time in UTC.
+ auto timestamp = UnixDateTime::now().milliseconds_since_epoch();
+
+ // 3. Let text be an empty string.
+ StringBuilder text;
+
+ // 4. If Type(args[0]) is String, and args[0] contains a formatting specifier, let formatted args be Formatter(args).
+ // Otherwise let formatted args be args.
+ // NB: The console runs the formatter before it gives the arguments to its client.
+
+ // 5. For each arg in formatted args:
+ for (size_t index = 0; index < args.size(); ++index) {
+ auto arg = args[index];
+
+ // 1. If arg is not the first entry in args, append a U+0020 SPACE to text.
+ if (index > 0)
+ text.append(' ');
+
+ // 2. If arg is a primitive ECMAScript value, append ToString(arg) to text. Otherwise append an
+ // implementation-defined string to text.
+ if (arg.is_symbol() || !arg.is_object())
+ text.append(arg.to_utf16_string_without_side_effects().to_utf8());
+ else if (arg.as_object().is_function())
+ text.append("function"sv);
+ else
+ text.append("Object"sv);
+ }
+
+ // 6. Let realm be the realm id of the current Realm Record.
+ // 7. Let serialized args be a new list.
+ JsonArray serialized_args;
+
+ // 8. Let serialization options be a map matching the script.SerializationOptions production with the fields set to
+ // their default values.
+ SerializationOptions serialization_options;
+
+ // 9. For each arg of args:
+ for (auto arg : args) {
+ // 1. Let serialized arg be the result of serialize as a remote value with arg as value, serialization options,
+ // none as ownership type, a new map as serialization internal map, realm and session.
+ // 2. Add serialized arg to serialized args.
+ serialized_args.must_append(serialize_as_a_remote_value(arg, serialization_options, ResultOwnership::None, settings));
+ }
+
+ // 10. Let source be the result of get the source given current Realm Record.
+ auto source = get_the_source(settings);
+
+ // 11. Let stack be the current stack trace.
+ auto stack = trace_stack.has_value() ? trace_stack.release_value() : current_stack_trace(vm);
+
+ // 12. Let entry be a map matching the log.ConsoleLogEntry production, with the the level field set to level, the
+ // text field set to text, the timestamp field set to timestamp, the stackTrace field set to stack, the method
+ // field set to method, the source field set to source, and the args field set to serialized args.
+ JsonObject entry;
+ entry.set("type"sv, "console"sv);
+ entry.set("level"sv, level);
+ entry.set("text"sv, text.to_string_without_validation());
+ entry.set("timestamp"sv, timestamp);
+ entry.set("stackTrace"sv, move(stack));
+ entry.set("method"sv, method);
+ entry.set("source"sv, move(source));
+ entry.set("args"sv, move(serialized_args));
+
+ // 13. Let body be a map matching the log.EntryAdded production, with the params field set to entry.
+ // 14. Let settings be the current settings object
+ // 15. Let related navigables be the result of get related navigables given settings.
+ // 16. If event is enabled with session, "log.entryAdded" and related navigables, emit an event with session and body.
+ // Otherwise, buffer a log event with session, related browsing contexts, and body.
+ // NB: WebDriver emits the event, or buffers it.
+ emit_event(*navigable, "log.entryAdded"_string, move(entry));
+}
+
+// https://w3c.github.io/webdriver-bidi/#event-log-entryAdded
+void error_reporting_steps(HTML::EnvironmentSettingsObject& settings, JS::Value exception)
+{
+ // 1. If handled is true return.
+ // NB: The caller only runs these steps for an error that is not handled.
+
+ // 2. Let settings be script's settings object.
+ auto navigable = related_navigable(settings);
+ if (!navigable)
+ return;
+
+ // 3. Let timestamp be a time value representing the current date and time in UTC.
+ auto timestamp = UnixDateTime::now().milliseconds_since_epoch();
+
+ // 4. Let stack be the stack trace for an exception with the exception corresponding to the error being reported.
+ auto stack = stack_trace_for_an_exception(exception);
+
+ // 5. Let source be the result of get the source given current Realm Record.
+ auto source = get_the_source(settings);
+
+ // NB: The message of an error is its name and message, as the error's toString() gives them.
+ auto message = textual_description_of_an_exception(settings, exception);
+
+ // 6. Let entry be a map matching the log.JavascriptLogEntry production, with level set to "error", text set to
+ // message, source set to source, timestamp set to timestamp, and the stackTrace field set to stack.
+ JsonObject entry;
+ entry.set("type"sv, "javascript"sv);
+ entry.set("level"sv, "error"sv);
+ entry.set("text"sv, move(message));
+ entry.set("source"sv, move(source));
+ entry.set("timestamp"sv, timestamp);
+ entry.set("stackTrace"sv, move(stack));
+
+ // 7. Let body be a map matching the log.EntryAdded production, with the params field set to entry.
+ // 8. Let related navigables be the result of get related navigables given settings.
+ // 9. For each session in active BiDi sessions:
+ // 1. If event is enabled with session, "log.entryAdded" and related navigables, emit an event with session and
+ // body.
+ // Otherwise, buffer a log event with session, related browsing contexts, and body.
+ // NB: WebDriver emits the event, or buffers it.
+ emit_event(*navigable, "log.entryAdded"_string, move(entry));
+}
+
+namespace {
+
+// NB: The console client of a realm whose console has none of its own, which only runs the console steps.
+class ConsoleStepsClient final : public JS::ConsoleClient {
+ GC_CELL(ConsoleStepsClient, JS::ConsoleClient);
+ GC_DECLARE_ALLOCATOR(ConsoleStepsClient);
+
+public:
+ explicit ConsoleStepsClient(JS::Console& console)
+ : ConsoleClient(console)
+ {
+ }
+
+ virtual void clear() override { }
+ virtual void end_group() override { }
+
+ virtual JS::ThrowCompletionOr<JS::Value> printer(JS::Console::LogLevel log_level, PrinterArguments arguments) override
+ {
+ console_steps(BindingsGlue::console_settings(*m_console), log_level, arguments);
+ return JS::js_undefined();
+ }
+};
+
+GC_DEFINE_ALLOCATOR(ConsoleStepsClient);
+
+}
+
+void ensure_console_steps_run_for(DOM::Document& document)
+{
+ // NB: A document that has a console client of its own runs the console steps through it.
+ if (document.console_client())
+ return;
+
+ auto& settings = document.relevant_settings_object();
+ auto& console = BindingsGlue::console_for(settings);
+ console.set_client(GC::Heap::the().allocate<ConsoleStepsClient>(console));
+}
+
+static void install_console_clients_for_existing_documents()
+{
+ for (auto navigable : HTML::all_local_navigables()) {
+ if (auto document = navigable->active_document())
+ ensure_console_steps_run_for(*document);
+ }
+}
+
+}
diff --git a/Libraries/LibWeb/WebDriver/BiDi/BiDi.h b/Libraries/LibWeb/WebDriver/BiDi/BiDi.h
new file mode 100644
index 00000000000..283a3c92606
--- /dev/null
+++ b/Libraries/LibWeb/WebDriver/BiDi/BiDi.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Function.h>
+#include <AK/JsonValue.h>
+#include <AK/Optional.h>
+#include <AK/String.h>
+#include <AK/Utf16String.h>
+#include <AK/kmalloc.h>
+#include <LibJS/Console.h>
+#include <LibJS/Forward.h>
+#include <LibURL/Forward.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
+#include <LibWebCommon/WebDriver/BiDi.h>
+
+// https://w3c.github.io/webdriver-bidi/
+// NB: The parts of a BiDi session that run in the process hosting a navigable's document. A process only does any of
+// this work while the browser process says a BiDi session is active, which only WebDriver can start.
+namespace Web::WebDriver::BiDi {
+
+WEB_API extern bool g_is_active;
+
+// Whether a BiDi session is active.
+inline bool is_active() { return g_is_active; }
+
+WEB_API void set_session_state(BiDiSessionState);
+WEB_API BiDiSessionState const& session_state();
+WEB_API bool is_event_enabled(StringView event_name);
+
+// Where this process reports the events of the navigables it hosts.
+struct WEB_API EventSink {
+ AK_ALLOC_WITH_KMALLOC;
+
+ Function<void(HTML::Navigable const&, String const& name, JsonValue params)> on_event;
+ Function<void(HTML::Navigable const&, StringView name, Optional<Utf16String> const& navigation_id, URL::URL const& url)> on_navigation_event;
+};
+WEB_API void set_event_sink(EventSink);
+
+// https://w3c.github.io/webdriver-bidi/#navigable-id
+WEB_API String navigable_id(HTML::Navigable const&);
+
+// https://w3c.github.io/webdriver-bidi/#emit-an-event
+// NB: The browser process emits the event for the sessions that enable it given the navigable it relates to.
+void emit_event(HTML::Navigable const&, String name, JsonValue params);
+
+// https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigation-status
+// NB: Reports the event that the WebDriver BiDi navigation status steps of a navigable emit, such as
+// "browsingContext.load". The browser process emits it.
+void navigation_event(HTML::Navigable const&, StringView event_name, Optional<Utf16String> const& navigation_id, URL::URL const&);
+
+// NB: The steps to run once a document is active in its navigable and before scripts may run for it: the document's
+// realm is created as far as WebDriver BiDi can tell, and the preload scripts run in it.
+WEB_API void document_is_ready_for_scripts(DOM::Document&);
+
+// https://w3c.github.io/webdriver-bidi/#event-script-realmDestroyed
+void unloading_document_cleanup_steps(DOM::Document&);
+
+// https://w3c.github.io/webdriver-bidi/#event-log-entryAdded
+WEB_API void console_steps(HTML::EnvironmentSettingsObject&, JS::Console::LogLevel, JS::ConsoleClient::PrinterArguments const&);
+void error_reporting_steps(HTML::EnvironmentSettingsObject&, JS::Value exception);
+
+// NB: A realm whose console has no client of its own gets one that only runs the console steps.
+void ensure_console_steps_run_for(DOM::Document&);
+
+}
diff --git a/Libraries/LibWeb/WebDriver/BiDi/BindingsGlue.h b/Libraries/LibWeb/WebDriver/BiDi/BindingsGlue.h
new file mode 100644
index 00000000000..523d7ae62c1
--- /dev/null
+++ b/Libraries/LibWeb/WebDriver/BiDi/BindingsGlue.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibJS/Console.h>
+#include <LibJS/Runtime/Array.h>
+#include <LibJS/Runtime/ConsoleObject.h>
+#include <LibJS/Runtime/Date.h>
+#include <LibJS/Runtime/Error.h>
+#include <LibJS/Runtime/Map.h>
+#include <LibJS/Runtime/NativeFunction.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibJS/Runtime/Set.h>
+#include <LibWeb/Bindings/Intrinsics.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/DOM/Node.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+
+namespace Web::WebDriver::BiDi::BindingsGlue {
+
+inline JS::Value wrap_node(HTML::EnvironmentSettingsObject& settings, DOM::Node& node)
+{
+ auto& realm = settings.realm();
+ return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { node });
+}
+
+inline GC::Ref<JS::Array> create_array(HTML::EnvironmentSettingsObject& settings, ReadonlySpan<JS::Value> values)
+{
+ return JS::Array::create_from(settings.realm(), values);
+}
+
+inline GC::Ref<JS::Date> create_date(HTML::EnvironmentSettingsObject& settings, double time)
+{
+ return JS::Date::create(settings.realm(), time);
+}
+
+inline GC::Ref<JS::Map> create_map(HTML::EnvironmentSettingsObject& settings)
+{
+ return JS::Map::create(settings.realm());
+}
+
+inline GC::Ref<JS::Set> create_set(HTML::EnvironmentSettingsObject& settings)
+{
+ return JS::Set::create(settings.realm());
+}
+
+inline GC::Ref<JS::Object> create_object(HTML::EnvironmentSettingsObject& settings)
+{
+ auto& realm = settings.realm();
+ return JS::Object::create(realm, realm.intrinsics().object_prototype());
+}
+
+inline GC::Ref<JS::NativeFunction> create_channel_function(HTML::EnvironmentSettingsObject& settings, Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> steps)
+{
+ return JS::NativeFunction::create(settings.realm(), move(steps), 1);
+}
+
+inline GC::Ref<JS::TypeError> create_preload_type_error(HTML::EnvironmentSettingsObject& settings)
+{
+ return JS::TypeError::create(settings.realm(), "Preload script is not a function"_utf16);
+}
+
+inline HTML::EnvironmentSettingsObject& console_settings(JS::Console& console)
+{
+ return HTML::principal_realm_settings_object(console.realm());
+}
+
+inline JS::Console& console_for(HTML::EnvironmentSettingsObject& settings)
+{
+ return settings.realm().intrinsics().console_object()->console();
+}
+
+}
diff --git a/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.cpp b/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.cpp
new file mode 100644
index 00000000000..80cf6359c8b
--- /dev/null
+++ b/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.cpp
@@ -0,0 +1,1616 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/GenericLexer.h>
+#include <AK/HashTable.h>
+#include <AK/JsonArray.h>
+#include <AK/Random.h>
+#include <AK/TemporaryChange.h>
+#include <LibCrypto/BigInt/SignedBigInteger.h>
+#include <LibGC/ConservativeVector.h>
+#include <LibJS/Runtime/AbstractOperations.h>
+#include <LibJS/Runtime/Array.h>
+#include <LibJS/Runtime/BigInt.h>
+#include <LibJS/Runtime/Date.h>
+#include <LibJS/Runtime/Error.h>
+#include <LibJS/Runtime/ErrorData.h>
+#include <LibJS/Runtime/Map.h>
+#include <LibJS/Runtime/NativeFunction.h>
+#include <LibJS/Runtime/Promise.h>
+#include <LibJS/Runtime/RegExpObject.h>
+#include <LibJS/Runtime/Set.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/DOM/Attr.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/Element.h>
+#include <LibWeb/DOM/HTMLCollection.h>
+#include <LibWeb/DOM/NamedNodeMap.h>
+#include <LibWeb/DOM/Node.h>
+#include <LibWeb/DOM/NodeList.h>
+#include <LibWeb/DOM/ShadowRoot.h>
+#include <LibWeb/HTML/BrowsingContext.h>
+#include <LibWeb/HTML/LocalNavigable.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Window.h>
+#include <LibWeb/HTML/WindowProxy.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
+#include <LibWeb/WebDriver/BiDi/BindingsGlue.h>
+#include <LibWeb/WebDriver/BiDi/RemoteValue.h>
+#include <LibWeb/WebDriver/BiDi/Script.h>
+#include <LibWeb/WebDriver/ElementReference.h>
+
+namespace Web::WebDriver::BiDi {
+
+static Error invalid_argument(StringView message)
+{
+ return Error::from_code(ErrorCode::InvalidArgument, message);
+}
+
+static String to_utf8(Utf16View view)
+{
+ return view.to_utf8_but_should_be_ported_to_utf16();
+}
+
+// https://w3c.github.io/webdriver-bidi/#type-script-ResultOwnership
+ErrorOr<ResultOwnership, Error> parse_result_ownership(JsonValue const& value)
+{
+ // script.ResultOwnership = "root" / "none"
+ if (value.is_string()) {
+ if (value.as_string() == "root"sv)
+ return ResultOwnership::Root;
+ if (value.as_string() == "none"sv)
+ return ResultOwnership::None;
+ }
+ return invalid_argument("Result ownership must be \"root\" or \"none\""sv);
+}
+
+// https://w3c.github.io/webdriver-bidi/#handle-object-map
+// Each ECMAScript Realm has a corresponding handle object map. This is a strong map from handle ids to their
+// corresponding objects.
+// NB: Keyed by realm id. The map of a window realm is cleared when its document is unloaded.
+// NB: A handle names an object or a symbol, which the map keeps alive.
+using HandleObjectMap = HashMap<String, GC::RootVector<JS::Value>>;
+static HashMap<String, HandleObjectMap>& handle_object_maps()
+{
+ static auto& maps = *new HashMap<String, HandleObjectMap>;
+ return maps;
+}
+
+// NB: The id of a realm that is not the realm of a window, which no document names.
+static HashMap<HTML::EnvironmentSettingsObject const*, String>& other_realm_ids()
+{
+ static auto& ids = *new HashMap<HTML::EnvironmentSettingsObject const*, String>;
+ return ids;
+}
+
+// https://w3c.github.io/webdriver-bidi/#realm-id
+// Each realm has an associated realm id, which is a string uniquely identifying that realm. This is implicitly set when
+// the realm is created.
+// NB: The realm of a window is named by the document that is its window's associated Document, which the browser
+// process routes commands to. A window that a new document reuses is a new realm for WebDriver BiDi.
+String realm_id(HTML::EnvironmentSettingsObject& settings)
+{
+ if (auto* window = HTML::window_from_global_object(settings.global_object())) {
+ auto id = window->associated_document().id();
+ return MUST(String::formatted("{}.{}", id.namespace_id, id.local_id));
+ }
+
+ return other_realm_ids().ensure(&settings, [] { return generate_random_uuid(); });
+}
+
+HTML::EnvironmentSettingsObject* settings_with_realm_id(HTML::Navigable& navigable, StringView id)
+{
+ auto* local_navigable = as_if<HTML::LocalNavigable>(navigable);
+ if (!local_navigable)
+ return nullptr;
+
+ auto document = local_navigable->active_document();
+ if (!document)
+ return nullptr;
+
+ auto& settings = document->relevant_settings_object();
+ if (realm_id(settings) != id)
+ return nullptr;
+ return &settings;
+}
+
+void clear_handle_object_map(HTML::EnvironmentSettingsObject& settings)
+{
+ handle_object_maps().remove(realm_id(settings));
+}
+
+void clear_all_handle_object_maps()
+{
+ handle_object_maps().clear();
+ other_realm_ids().clear();
+}
+
+bool remove_handle(HTML::EnvironmentSettingsObject& settings, StringView handle_id)
+{
+ auto map = handle_object_maps().find(realm_id(settings));
+ if (map == handle_object_maps().end())
+ return false;
+ return map->value.remove(handle_id);
+}
+
+// https://w3c.github.io/webdriver-bidi/#serialize-primitive-protocol-value
+static Optional<JsonObject> serialize_primitive_protocol_value(JS::Value value)
+{
+ // 1. Let remote value be undefined.
+ JsonObject remote_value;
+
+ // 2. In the following list of conditions and associated steps, run the first set of steps for which the associated
+ // condition is true, if any:
+ // -> Type(value) is undefined
+ if (value.is_undefined()) {
+ // Let remote value be a map matching the script.UndefinedValue production in the local end definition.
+ remote_value.set("type"sv, "undefined"sv);
+ }
+ // -> Type(value) is Null
+ else if (value.is_null()) {
+ // Let remote value be a map matching the script.NullValue production in the local end definition.
+ remote_value.set("type"sv, "null"sv);
+ }
+ // -> Type(value) is String
+ else if (value.is_string()) {
+ // Let remote value be a map matching the script.StringValue production in the local end definition, with the
+ // value property set to value.
+ remote_value.set("type"sv, "string"sv);
+ remote_value.set("value"sv, to_utf8(value.as_string().utf16_string_view()));
+ }
+ // -> Type(value) is Number
+ else if (value.is_number()) {
+ // 1. Switch on the value of value:
+ JsonValue serialized;
+ auto number = value.as_double();
+ // NaN
+ if (isnan(number))
+ serialized = "NaN"sv;
+ // -0
+ else if (value.is_negative_zero())
+ serialized = "-0"sv;
+ // Infinity
+ else if (value.is_positive_infinity())
+ serialized = "Infinity"sv;
+ // -Infinity
+ else if (value.is_negative_infinity())
+ serialized = "-Infinity"sv;
+ // Otherwise:
+ else if (value.is_int32())
+ serialized = value.as_i32();
+ else
+ serialized = number;
+
+ // 2. Let remote value be a map matching the script.NumberValue production in the local end definition, with the
+ // value property set to serialized.
+ remote_value.set("type"sv, "number"sv);
+ remote_value.set("value"sv, move(serialized));
+ }
+ // -> Type(value) is Boolean
+ else if (value.is_boolean()) {
+ // Let remote value be a map matching the script.BooleanValue production in the local end definition, with the
+ // value property set to value.
+ remote_value.set("type"sv, "boolean"sv);
+ remote_value.set("value"sv, value.as_bool());
+ }
+ // -> Type(value) is BigInt
+ else if (value.is_bigint()) {
+ // Let remote value be a map matching the script.BigIntValue production in the local end definition, with the
+ // value property set to the result of running the ToString operation on value.
+ remote_value.set("type"sv, "bigint"sv);
+ remote_value.set("value"sv, MUST(value.as_bigint().big_integer().to_base(10)));
+ } else {
+ return {};
+ }
+
+ // 3. Return remote value
+ return remote_value;
+}
+
+// The ISO 8601 string of a time value, as Date.prototype.toISOString gives it.
+static String date_to_iso_string(double time_value)
+{
+ auto year = JS::year_from_time(time_value);
+ StringBuilder builder;
+ if (year >= 0 && year <= 9999)
+ builder.appendff("{:04}", year);
+ else
+ builder.appendff("{}{:06}", year < 0 ? '-' : '+', AK::abs(year));
+ builder.appendff("-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
+ JS::month_from_time(time_value) + 1,
+ JS::date_from_time(time_value),
+ JS::hour_from_time(time_value),
+ JS::min_from_time(time_value),
+ JS::sec_from_time(time_value),
+ JS::ms_from_time(time_value));
+ return builder.to_string_without_validation();
+}
+
+namespace {
+
+// NB: A serialization gives every object it may name twice a marker as its internalId, and then the internalId of each
+// object it named twice, or removes the marker of one it named once. The internal id of a remote value is known
+// only once the value is serialized again.
+struct Serializer {
+ GC::Ref<HTML::EnvironmentSettingsObject> settings;
+
+ // NB: The depth of the remote value being serialized, which an object graph of web content decides.
+ size_t depth { 0 };
+
+ // https://w3c.github.io/webdriver-bidi/#serialization-internal-map
+ // NB: The objects of the map are kept alive, as serializing may run script that drops them, so that the address of
+ // an object is not reused for another one while the map names it.
+ HashMap<GC::RawPtr<JS::Object const>, u64> serialization_internal_map;
+ GC::RootVector<JS::Value> serialized_objects;
+ HashTable<u64> duplicated_markers;
+ u64 next_marker { 0 };
+
+ JsonValue serialize_as_a_remote_value(JS::Value, SerializationOptions const&, ResultOwnership);
+ JsonArray serialize_as_a_list(GC::RootVector<JS::Value> const&, SerializationOptions const&, ResultOwnership);
+ JsonArray serialize_as_a_mapping(GC::ConservativeVector<Array<JS::Value, 2>> const&, SerializationOptions const&, ResultOwnership);
+ JsonObject serialize_an_array_like(StringView type, Optional<String> handle_id, bool known_object, JS::Object const& value, GC::RootVector<JS::Value> const& items, SerializationOptions const&, ResultOwnership);
+ Optional<String> handle_for_an_object(ResultOwnership, JS::Value);
+ void set_internal_ids_if_needed(JsonObject& remote_value, JS::Object const&);
+ void assign_internal_ids(JsonValue&);
+
+ HashMap<u64, String> internal_ids;
+};
+
+}
+
+static String marker_string(u64 marker)
+{
+ return MUST(String::formatted("{}", marker));
+}
+
+// https://w3c.github.io/webdriver-bidi/#handle-for-an-object
+Optional<String> Serializer::handle_for_an_object(ResultOwnership ownership_type, JS::Value object)
+{
+ // 1. If ownership type is equal "none", return null.
+ if (ownership_type == ResultOwnership::None)
+ return {};
+
+ // 2. Let handle id be a new, unique, string handle for object.
+ auto handle_id = generate_random_uuid();
+
+ // 3. Let handle map be realm's handle object map
+ // 4. Set handle map[handle id] to object.
+ GC::RootVector<JS::Value> root;
+ root.append(object);
+ handle_object_maps().ensure(realm_id(*settings)).set(handle_id, move(root));
+
+ // 5. Return handle id as a result.
+ return handle_id;
+}
+
+// https://w3c.github.io/webdriver-bidi/#set-internal-ids-if-needed
+void Serializer::set_internal_ids_if_needed(JsonObject& remote_value, JS::Object const& object)
+{
+ // 1. If the serialization internal map does not contain object, set serialization internal map[object] to remote
+ // value.
+ auto it = serialization_internal_map.find(&object);
+ if (it == serialization_internal_map.end()) {
+ auto marker = next_marker++;
+ serialization_internal_map.set(&object, marker);
+ serialized_objects.append(JS::Value { const_cast<JS::Object*>(&object) });
+ remote_value.set("internalId"sv, marker_string(marker));
+ return;
+ }
+
+ // 2. Otherwise, run the following steps:
+ // 1. Let previously serialized remote value be serialization internal map[object].
+ // 2. If previously serialized remote value does not have a field internalId, run the following steps:
+ // 1. Let internal id be the string representation of a UUID based on truly random, or pseudo-random numbers.
+ // 2. Set the internalId field of previously serialized remote value to internal id.
+ // 3. Set the internalId field of remote value to a field internalId in previously serialized remote value.
+ duplicated_markers.set(it->value);
+ remote_value.set("internalId"sv, marker_string(it->value));
+}
+
+static void for_each_child_remote_value(JsonObject& remote_value, Function<void(JsonValue&)> const& callback)
+{
+ auto type = remote_value.get_string("type"sv);
+ if (!type.has_value())
+ return;
+
+ if (type->is_one_of("array"sv, "set"sv, "nodelist"sv, "htmlcollection"sv)) {
+ if (auto list = remote_value.get_array("value"sv); list.has_value())
+ list->for_each([&](JsonValue& item) { callback(item); });
+ } else if (type->is_one_of("map"sv, "object"sv)) {
+ if (auto mapping = remote_value.get_array("value"sv); mapping.has_value()) {
+ mapping->for_each([&](JsonValue& entry) {
+ if (!entry.is_array())
+ return;
+ entry.as_array().for_each([&](JsonValue& key_or_value) {
+ if (key_or_value.is_object())
+ callback(key_or_value);
+ });
+ });
+ }
+ } else if (*type == "node"sv) {
+ if (auto properties = remote_value.get_object("value"sv); properties.has_value()) {
+ if (auto children = properties->get_array("children"sv); children.has_value())
+ children->for_each([&](JsonValue& child) { callback(child); });
+ if (auto shadow_root = properties->get("shadowRoot"sv); shadow_root.has_value() && shadow_root->is_object())
+ callback(*shadow_root);
+ }
+ }
+}
+
+void Serializer::assign_internal_ids(JsonValue& value)
+{
+ if (!value.is_object())
+ return;
+ auto& remote_value = value.as_object();
+
+ if (auto marker_value = remote_value.get_string("internalId"sv); marker_value.has_value()) {
+ auto marker = marker_value->to_number<u64>().value();
+ if (duplicated_markers.contains(marker))
+ remote_value.set("internalId"sv, internal_ids.ensure(marker, [] { return generate_random_uuid(); }));
+ else
+ remote_value.remove("internalId"sv);
+ }
+
+ for_each_child_remote_value(remote_value, [&](JsonValue& child) {
+ assign_internal_ids(child);
+ });
+}
+
+static SerializationOptions child_serialization_options_for_object_depth(SerializationOptions const& options)
+{
+ // 1. Let child serialization options be a clone of serialization options.
+ auto child_serialization_options = options;
+
+ // 2. If child serialization options["maxObjectDepth"] is not null, set child serialization options["maxObjectDepth"]
+ // to child serialization options["maxObjectDepth"] - 1.
+ if (child_serialization_options.max_object_depth.has_value())
+ child_serialization_options.max_object_depth = *child_serialization_options.max_object_depth - 1;
+
+ return child_serialization_options;
+}
+
+// https://w3c.github.io/webdriver-bidi/#serialize-as-a-list
+JsonArray Serializer::serialize_as_a_list(GC::RootVector<JS::Value> const& values, SerializationOptions const& serialization_options, ResultOwnership ownership_type)
+{
+ // 1. If serialization options["maxObjectDepth"] is not null, assert: serialization options["maxObjectDepth"] is
+ // greater than 0.
+ VERIFY(!serialization_options.max_object_depth.has_value() || *serialization_options.max_object_depth > 0);
+
+ // 2. Let serialized be a new list.
+ JsonArray serialized;
+
+ // 3. For each child value in IteratorToList(GetIterator(iterable, sync)):
+ for (auto child_value : values) {
+ // 1. Let child serialization options be a clone of serialization options.
+ // 2. If child serialization options["maxObjectDepth"] is not null, set child serialization
+ // options["maxObjectDepth"] to child serialization options["maxObjectDepth"] - 1.
+ auto child_serialization_options = child_serialization_options_for_object_depth(serialization_options);
+
+ // 3. Let serialized child be the result of serialize as a remote value with child value, child serialization
+ // options, ownership type, serialization internal map, realm, and session.
+ // 4. Append serialized child to serialized.
+ serialized.must_append(serialize_as_a_remote_value(child_value, child_serialization_options, ownership_type));
+ }
+
+ // 4. Return serialized
+ return serialized;
+}
+
+// https://w3c.github.io/webdriver-bidi/#serialize-as-a-mapping
+JsonArray Serializer::serialize_as_a_mapping(GC::ConservativeVector<Array<JS::Value, 2>> const& items, SerializationOptions const& serialization_options, ResultOwnership ownership_type)
+{
+ // 1. If serialization options["maxObjectDepth"] is not null, assert: serialization options["maxObjectDepth"] is
+ // greater than 0.
+ VERIFY(!serialization_options.max_object_depth.has_value() || *serialization_options.max_object_depth > 0);
+
+ // 2. Let serialized be a new list.
+ JsonArray serialized;
+
+ // 3. For item in IteratorToList(GetIterator(iterable, sync)):
+ for (auto const& item : items) {
+ // 1. Assert: IsArray(item)
+ // 2. Let property be CreateListFromArrayLike(item)
+ // 3. Assert: property is a list of size 2
+ // 4. Let key be property[0] and let value be property[1]
+ auto key = item[0];
+ auto value = item[1];
+
+ // 5. Let child serialization options be a clone of serialization options.
+ // 6. If child serialization options["maxObjectDepth"] is not null, set child serialization
+ // options["maxObjectDepth"] to child serialization options["maxObjectDepth"] - 1.
+ auto child_serialization_options = child_serialization_options_for_object_depth(serialization_options);
+
+ // 7. If Type(key) is String, let serialized key be child key, otherwise let serialized key be the result of
+ // serialize as a remote value with child key, child serialization options, ownership type, serialization
+ // internal map, realm, and session.
+ JsonValue serialized_key;
+ if (key.is_string())
+ serialized_key = to_utf8(key.as_string().utf16_string_view());
+ else
+ serialized_key = serialize_as_a_remote_value(key, child_serialization_options, ownership_type);
+
+ // 8. Let serialized value be the result of serialize as a remote value with value, child serialization options,
+ // ownership type, serialization internal map, realm, and session.
+ auto serialized_value = serialize_as_a_remote_value(value, child_serialization_options, ownership_type);
+
+ // 9. Let serialized child be («serialized key, serialized value»).
+ JsonArray serialized_child;
+ serialized_child.must_append(move(serialized_key));
+ serialized_child.must_append(move(serialized_value));
+
+ // 10. Append serialized child to serialized.
+ serialized.must_append(move(serialized_child));
+ }
+
+ // 4. Return serialized
+ return serialized;
+}
+
+// https://w3c.github.io/webdriver-bidi/#serialize-an-array-like
+JsonObject Serializer::serialize_an_array_like(StringView production, Optional<String> handle_id, bool known_object, JS::Object const& value, GC::RootVector<JS::Value> const& items, SerializationOptions const& serialization_options, ResultOwnership ownership_type)
+{
+ // 1. Let remote value be a map matching production, with the handle property set to handle id if it's not null, or
+ // omitted otherwise.
+ JsonObject remote_value;
+ remote_value.set("type"sv, production);
+ if (handle_id.has_value())
+ remote_value.set("handle"sv, handle_id.release_value());
+
+ // 2. Set internal ids if needed with serialization internal map, remote value and value.
+ set_internal_ids_if_needed(remote_value, value);
+
+ // 3. If known object is false, and serialization options["maxObjectDepth"] is not 0:
+ if (!known_object && serialization_options.max_object_depth != 0u) {
+ // 1. Let serialized be the result of serialize as a list with CreateArrayIterator(value, value), serialization
+ // options, ownership type, serialization internal map, realm, and session.
+ // 2. If serialized is not null, set field value of remote value to serialized.
+ remote_value.set("value"sv, serialize_as_a_list(items, serialization_options, ownership_type));
+ }
+
+ // 4. Return remote value
+ return remote_value;
+}
+
+// NB: The elements of an Array-like that CreateArrayIterator visits.
+static GC::RootVector<JS::Value> array_like_items(JS::VM& vm, JS::Object const& object)
+{
+ // AD-HOC: The length of an Array-like does not need to match the elements it has, so the remote value of one lists
+ // this many elements at most.
+ static constexpr size_t MAXIMUM_ITEMS = 1 << 16;
+
+ GC::RootVector<JS::Value> items;
+ auto length_value = object.get(vm.names.length);
+ if (length_value.is_error())
+ return items;
+ auto length = length_value.value().to_length(vm);
+ if (length.is_error())
+ return items;
+ for (size_t index = 0; index < min<size_t>(length.value(), MAXIMUM_ITEMS); ++index) {
+ auto item = object.get(JS::PropertyKey { index });
+ items.append(item.is_error() ? JS::js_undefined() : item.value());
+ }
+ return items;
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-shared-id-for-a-node
+static Optional<String> get_shared_id_for_a_node(DOM::Node const& node)
+{
+ // 1. Let node be unwrapped node.
+ // 2. If node does not implement Node, return null.
+ // 3. Let navigable be node's node navigable.
+ auto navigable = node.navigable();
+
+ // 4. If navigable is null, return null.
+ if (!navigable || !navigable->active_browsing_context())
+ return {};
+
+ // 5. Return get or create a node reference with session, navigable and node.
+ return get_or_create_a_node_reference(*navigable->active_browsing_context(), node);
+}
+
+// https://w3c.github.io/webdriver-bidi/#serialize-as-a-remote-value
+JsonValue Serializer::serialize_as_a_remote_value(JS::Value value, SerializationOptions const& serialization_options, ResultOwnership ownership_type)
+{
+ auto& vm = settings->global_object().vm();
+
+ // AD-HOC: A remote value deeper than this is serialized as if the serialization options allowed no deeper objects
+ // and nodes, so that serializing it does not exhaust the stack, and its JSON can be parsed.
+ static constexpr size_t MAXIMUM_DEPTH = 100;
+ TemporaryChange depth_change { depth, depth + 1 };
+ if (depth > MAXIMUM_DEPTH && (serialization_options.max_object_depth != 0u || serialization_options.max_dom_depth != 0u)) {
+ auto limited_serialization_options = serialization_options;
+ limited_serialization_options.max_object_depth = 0;
+ limited_serialization_options.max_dom_depth = 0;
+ return serialize_as_a_remote_value(value, limited_serialization_options, ownership_type);
+ }
+
+ // 1. Let remote value be a result of serialize primitive protocol value given a value.
+ // 2. If remote value is not undefined, return remote value.
+ if (auto remote_value = serialize_primitive_protocol_value(value); remote_value.has_value())
+ return remote_value.release_value();
+
+ JsonObject remote_value;
+
+ // 3. Let handle id be the handle for an object with realm, ownership type and value.
+ auto handle_id = handle_for_an_object(ownership_type, value);
+
+ // -> Type(value) is Symbol
+ if (value.is_symbol()) {
+ // Let remote value be a map matching the script.SymbolRemoteValue production in the local end definition, with
+ // the handle property set to handle id if it's not null, or omitted otherwise.
+ remote_value.set("type"sv, "symbol"sv);
+ if (handle_id.has_value())
+ remote_value.set("handle"sv, handle_id.release_value());
+ return remote_value;
+ }
+
+ VERIFY(value.is_object());
+ auto& object = value.as_object();
+
+ // 4. Set ownership type to "none".
+ ownership_type = ResultOwnership::None;
+
+ // 5. Let known object be true, if value is in the serialization internal map, otherwise false.
+ auto known_object = serialization_internal_map.contains(&object);
+
+ auto set_handle = [&](JsonObject& remote_value) {
+ if (handle_id.has_value())
+ remote_value.set("handle"sv, *handle_id);
+ };
+
+ auto simple = [&](StringView type) {
+ JsonObject remote_value;
+ remote_value.set("type"sv, type);
+ set_handle(remote_value);
+ return remote_value;
+ };
+
+ // 6. In the following list of conditions and associated steps, run the first set of steps for which the associated
+ // condition is true:
+ // -> IsArray(value)
+ if (auto is_array = value.is_array(vm); !is_array.is_error() && is_array.value()) {
+ // Let remote value be serialize an Array-like with session, script.ArrayRemoteValue, handle id, known object,
+ // value, serialization options, ownership type, serialization internal map, realm, and session.
+ GC::RootVector<JS::Value> items;
+ if (!known_object && serialization_options.max_object_depth != 0u)
+ items = array_like_items(vm, object);
+ return serialize_an_array_like("array"sv, move(handle_id), known_object, object, items, serialization_options, ownership_type);
+ }
+
+ // -> IsRegExp(value)
+ // NB: This does not get @@match, which would run script.
+ if (auto const* regexp = as_if<JS::RegExpObject>(object)) {
+ // 1. Let pattern be ToString(Get(value, "source")).
+ // 2. Let flags be ToString(Get(value, "flags")).
+ // NB: These are the source and flags the RegExp object has, without running script.
+ auto pattern = to_utf8(regexp->pattern());
+ auto flags = to_utf8(regexp->flags());
+
+ // 3. Let serialized be a map matching the script.RegExpValue production in the local end definition, with the
+ // pattern property set to the pattern and the the flags property set to the flags.
+ JsonObject serialized;
+ serialized.set("pattern"sv, move(pattern));
+ serialized.set("flags"sv, move(flags));
+
+ // 4. Let remote value be a map matching the script.RegExpRemoteValue production in the local end definition,
+ // with the handle property set to handle id if it's not null, or omitted otherwise, and the value property set
+ // to serialized.
+ auto remote_value = simple("regexp"sv);
+ remote_value.set("value"sv, move(serialized));
+ return remote_value;
+ }
+
+ // -> value has a [[DateValue]] internal slot.
+ if (auto const* date = as_if<JS::Date>(object)) {
+ // 1. Set serialized to Call(Date.prototype.toISOString, value).
+ // 2. Assert: serialized is not a throw completion.
+ // NB: toISOString throws a RangeError for an invalid date.
+ auto remote_value = simple("date"sv);
+ if (isfinite(date->date_value()))
+ remote_value.set("value"sv, date_to_iso_string(date->date_value()));
+ else
+ remote_value.set("value"sv, "Invalid Date"sv);
+
+ // 3. Let remote value be a map matching the script.DateRemoteValue production in the local end definition, with
+ // the handle property set to handle id if it's not null, or omitted otherwise, and the value set to
+ // serialized.
+ return remote_value;
+ }
+
+ // -> value has a [[MapData]] internal slot
+ if (auto const* map = as_if<JS::Map>(object)) {
+ // 1. Let remote value be a map matching the script.MapRemoteValue production in the local end definition, with
+ // the handle property set to handle id if it's not null, or omitted otherwise.
+ auto remote_value = simple("map"sv);
+
+ // 2. Set internal ids if needed with serialization internal map, remote value and value.
+ set_internal_ids_if_needed(remote_value, object);
+
+ // 3. Let serialized be null.
+ // 4. If known object is false, and serialization options["maxObjectDepth"] is not 0, run the following steps:
+ if (!known_object && serialization_options.max_object_depth != 0u) {
+ // 1. Let serialized be the result of serialize as a mapping with CreateMapIterator(value, key+value),
+ // serialization options, ownership type, serialization internal map, realm, and session.
+ GC::ConservativeVector<Array<JS::Value, 2>> entries;
+ GC::RootVector<JS::Value> roots;
+ (void)map->for_each_entry([&](JS::Value key, JS::Value entry_value) -> JS::ThrowCompletionOr<void> {
+ roots.append(key);
+ roots.append(entry_value);
+ entries.append({ key, entry_value });
+ return {};
+ });
+
+ // 5. If serialized is not null, set field value of remote value to serialized.
+ remote_value.set("value"sv, serialize_as_a_mapping(entries, serialization_options, ownership_type));
+ }
+ return remote_value;
+ }
+
+ // -> value has a [[SetData]] internal slot
+ if (auto const* set = as_if<JS::Set>(object)) {
+ // 1. Let remote value be a map matching the script.SetRemoteValue production in the local end definition, with
+ // the handle property set to handle id if it's not null, or omitted otherwise.
+ auto remote_value = simple("set"sv);
+
+ // 2. Set internal ids if needed with serialization internal map, remote value and value.
+ set_internal_ids_if_needed(remote_value, object);
+
+ // 3. Let serialized be null.
+ // 4. If known object is false, and serialization options["maxObjectDepth"] is not 0, run the following steps:
+ if (!known_object && serialization_options.max_object_depth != 0u) {
+ // 1. Let serialized be the result of serialize as a list with CreateSetIterator(value, value), serialization
+ // options, ownership type, serialization internal map, realm, and session.
+ GC::RootVector<JS::Value> values;
+ (void)set->for_each_value([&](JS::Value entry) -> JS::ThrowCompletionOr<void> {
+ values.append(entry);
+ return {};
+ });
+
+ // 5. If serialized is not null, set field value of remote value to serialized.
+ remote_value.set("value"sv, serialize_as_a_list(values, serialization_options, ownership_type));
+ }
+ return remote_value;
+ }
+
+ // -> value has a [[WeakMapData]] internal slot
+ if (object.is_weak_map())
+ return simple("weakmap"sv);
+
+ // -> value has a [[WeakSetData]] internal slot
+ if (object.is_weak_set())
+ return simple("weakset"sv);
+
+ // -> value has a [[GeneratorState]] internal slot or [[AsyncGeneratorState]] internal slot
+ if (object.is_generator())
+ return simple("generator"sv);
+
+ // -> value has an [[ErrorData]] internal slot
+ // NB: A platform object such as a DOMException exposes error data too, but has no [[ErrorData]] internal slot.
+ if (!object.is_platform_object() && object.has_error_data())
+ return simple("error"sv);
+
+ // -> value has a [[ProxyHandler]] internal slot and a [[ProxyTarget]] internal slot
+ if (object.is_proxy())
+ return simple("proxy"sv);
+
+ // -> IsPromise(value)
+ if (is<JS::Promise>(object))
+ return simple("promise"sv);
+
+ // -> value has a [[TypedArrayName]] internal slot
+ if (object.is_typed_array())
+ return simple("typedarray"sv);
+
+ // -> value has an [[ArrayBufferData]] internal slot
+ if (object.is_array_buffer())
+ return simple("arraybuffer"sv);
+
+ // -> value is a platform object that implements NodeList
+ if (Bindings::impl_from<DOM::NodeList>(&object)) {
+ // Let remote value be serialize an Array-like with script.NodeListRemoteValue, handle id, known object, value,
+ // serialization options, ownership type, serialization internal map, realm, and session.
+ GC::RootVector<JS::Value> items;
+ if (!known_object && serialization_options.max_object_depth != 0u)
+ items = array_like_items(vm, object);
+ return serialize_an_array_like("nodelist"sv, move(handle_id), known_object, object, items, serialization_options, ownership_type);
+ }
+
+ // -> value is a platform object that implements HTMLCollection
+ if (Bindings::impl_from<DOM::HTMLCollection>(&object)) {
+ // Let remote value be serialize an Array-like with script.HTMLCollectionRemoteValue, handle id, known object,
+ // value, serialization options, ownership type, known object, serialization internal map, realm, and session.
+ GC::RootVector<JS::Value> items;
+ if (!known_object && serialization_options.max_object_depth != 0u)
+ items = array_like_items(vm, object);
+ return serialize_an_array_like("htmlcollection"sv, move(handle_id), known_object, object, items, serialization_options, ownership_type);
+ }
+
+ // -> value is a platform object that implements Node
+ if (auto* node = Bindings::impl_from<DOM::Node>(&object)) {
+ // 1. Let shared id be get shared id for a node with value and session.
+ auto shared_id = get_shared_id_for_a_node(*node);
+
+ // 2. Let remote value be a map matching the script.NodeRemoteValue production in the local end definition, with
+ // the sharedId property set to shared id if it's not null, or omitted otherwise, and the handle property set
+ // to handle id if it's not null, or omitted otherwise.
+ auto remote_value = simple("node"sv);
+ if (shared_id.has_value())
+ remote_value.set("sharedId"sv, shared_id.release_value());
+
+ // 3. Set internal ids if needed with serialization internal map, remote value and value.
+ set_internal_ids_if_needed(remote_value, object);
+
+ // 4. Let serialized be null.
+ // 5. If known object is false, run the following steps:
+ if (!known_object) {
+ // 1. Let serialized be a map.
+ JsonObject serialized;
+
+ // 2. Set serialized["nodeType"] to Get(value, "nodeType").
+ serialized.set("nodeType"sv, node->node_type());
+
+ // 3. Set node value to Get(value, "nodeValue").
+ // 4. If node value is not null set serialized["nodeValue"] to node value.
+ if (auto node_value = node->node_value(); node_value.has_value())
+ serialized.set("nodeValue"sv, to_utf8(*node_value));
+
+ // 5. If value implements Element or Attr:
+ if (auto const* element = as_if<DOM::Element>(*node)) {
+ // 1. Set serialized["localName"] to Get(value, "localName").
+ serialized.set("localName"sv, to_utf8(element->local_name()));
+
+ // 2. Set serialized["namespaceURI"] to Get(value, "namespaceURI")
+ if (auto const& namespace_uri = element->namespace_uri(); namespace_uri.has_value())
+ serialized.set("namespaceURI"sv, to_utf8(*namespace_uri));
+ else
+ serialized.set("namespaceURI"sv, JsonValue {});
+ } else if (auto const* attr = as_if<DOM::Attr>(*node)) {
+ serialized.set("localName"sv, to_utf8(attr->local_name()));
+ if (auto const& namespace_uri = attr->namespace_uri(); namespace_uri.has_value())
+ serialized.set("namespaceURI"sv, to_utf8(*namespace_uri));
+ else
+ serialized.set("namespaceURI"sv, JsonValue {});
+ }
+
+ // 6. Let child node count be the size of value's children.
+ // 7. Set serialized["childNodeCount"] to child node count.
+ serialized.set("childNodeCount"sv, node->child_count());
+
+ // 8. If serialization options["maxDomDepth"] is equal to 0, or if value implements ShadowRoot and
+ // serialization options["includeShadowTree"] is "none", or if serialization options["includeShadowTree"]
+ // is "open" and value's mode is "closed", let children be null.
+ auto const* shadow_root = as_if<DOM::ShadowRoot>(*node);
+ bool children_are_null = serialization_options.max_dom_depth == 0u
+ || (shadow_root && serialization_options.include_shadow_tree == SerializationOptions::IncludeShadowTree::None)
+ || (shadow_root && serialization_options.include_shadow_tree == SerializationOptions::IncludeShadowTree::Open && shadow_root->mode() == Bindings::ShadowRootMode::Closed);
+
+ // Otherwise, let children be an empty list and, for each node child in the children of value:
+ if (!children_are_null) {
+ JsonArray children;
+ for (auto* child = node->first_child(); child; child = child->next_sibling()) {
+ // 1. Let child serialization options be a clone of serialization options.
+ auto child_serialization_options = serialization_options;
+
+ // 2. If child serialization options["maxDomDepth"] is not null, set child serialization
+ // options["maxDomDepth"] to child serialization options["maxDomDepth"] - 1.
+ if (child_serialization_options.max_dom_depth.has_value())
+ child_serialization_options.max_dom_depth = *child_serialization_options.max_dom_depth - 1;
+
+ // 3. Let serialized be the result of serialize as a remote value with child, child serialization
+ // options, ownership type, serialization internal map, realm, and session.
+ // 4. Append serialized to children.
+ auto child_value = BindingsGlue::wrap_node(*settings, *child);
+ children.must_append(serialize_as_a_remote_value(child_value, child_serialization_options, ownership_type));
+ }
+
+ // 9. If children is not null, set serialized["children"] to children.
+ serialized.set("children"sv, move(children));
+ }
+
+ // 10. If value implements Element:
+ if (auto* element = as_if<DOM::Element>(*node)) {
+ // 1. Let attributes be a new map.
+ JsonObject attributes;
+
+ // 2. For each attribute in value's attribute list:
+ element->for_each_attribute([&](DOM::Attr const& attribute) {
+ // 1. Let name be attribute's qualified name
+ // 2. Let value be attribute's value.
+ // 3. Set attributes[name] to value
+ attributes.set(to_utf8(attribute.name()), to_utf8(attribute.value()));
+ });
+
+ // 3. Set serialized["attributes"] to attributes.
+ serialized.set("attributes"sv, move(attributes));
+
+ // 4. Let shadow root be value's shadow root.
+ // 5. If shadow root is null, let serialized shadow be null. Otherwise run the following substeps:
+ JsonValue serialized_shadow;
+ if (auto element_shadow_root = element->shadow_root()) {
+ // 1. Let serialized shadow be the result of serialize as a remote value with shadow root, serialization
+ // options, ownership type, serialization internal map, realm, and session.
+ auto shadow_root_value = BindingsGlue::wrap_node(*settings, *element_shadow_root);
+ serialized_shadow = serialize_as_a_remote_value(shadow_root_value, serialization_options, ownership_type);
+ }
+
+ // 6. Set serialized["shadowRoot"] to serialized shadow.
+ serialized.set("shadowRoot"sv, move(serialized_shadow));
+ }
+
+ // 11. If value implements ShadowRoot, set serialized["mode"] to value's mode.
+ if (shadow_root)
+ serialized.set("mode"sv, shadow_root->mode() == Bindings::ShadowRootMode::Closed ? "closed"sv : "open"sv);
+
+ // 6. If serialized is not null, set field value of remote value to serialized.
+ remote_value.set("value"sv, move(serialized));
+ }
+
+ return remote_value;
+ }
+
+ // -> value is a platform object that implements WindowProxy
+ if (auto* window_proxy = HTML::WindowProxy::from_object(object)) {
+ // 1. Let window be the value of value's [[WindowProxy]] internal slot.
+ // 2. Let navigable be window's navigable.
+ auto navigable = window_proxy->navigable();
+
+ // 3. Let navigable id be the navigable id for navigable.
+ // 4. Let serialized be a map matching the script.WindowProxyProperties production in the local end definition
+ // with the context property set to navigable id.
+ JsonObject serialized;
+ if (navigable)
+ serialized.set("context"sv, navigable_id(*navigable));
+ else
+ serialized.set("context"sv, JsonValue {});
+
+ // 5. Let remote value be a map matching the script.WindowProxyRemoteValue production in the local end
+ // definition, with the handle property set to handle id if it's not null, or omitted otherwise, and the value
+ // property set to serialized.
+ auto remote_value = simple("window"sv);
+ remote_value.set("value"sv, move(serialized));
+ return remote_value;
+ }
+
+ // -> value is a platform object
+ if (object.is_platform_object()) {
+ // Let remote value be a map matching the script.ObjectRemoteValue production in the local end definition, with
+ // the handle property set to handle id if it's not null, or omitted otherwise.
+ return simple("object"sv);
+ }
+
+ // -> IsCallable(value)
+ if (object.is_function()) {
+ // Let remote value be a map matching the script.FunctionRemoteValue production in the local end definition,
+ // with the handle property set to handle id if it's not null, or omitted otherwise.
+ return simple("function"sv);
+ }
+
+ // -> Otherwise:
+ // 1. Assert: Type(value) is Object
+ // 2. Let remote value be a map matching the script.ObjectRemoteValue production in the local end definition, with
+ // the handle property set to handle id if it's not null, or omitted otherwise.
+ remote_value = simple("object"sv);
+
+ // 3. Set internal ids if needed with serialization internal map, remote value and value.
+ set_internal_ids_if_needed(remote_value, object);
+
+ // 4. Let serialized be null.
+ // 5. If known object is false, and serialization options["maxObjectDepth"] is not 0, run the following steps:
+ if (!known_object && serialization_options.max_object_depth != 0u) {
+ // 1. Let serialized be the result of serialize as a mapping with EnumerableOwnPropertyNames(value, key+value),
+ // serialization options, ownership type, serialization internal map, realm, and session.
+ GC::ConservativeVector<Array<JS::Value, 2>> entries;
+ GC::RootVector<JS::Value> roots;
+ if (auto properties = object.enumerable_own_property_names(JS::Object::PropertyKind::KeyAndValue); !properties.is_error()) {
+ for (auto property : properties.value()) {
+ auto& entry = property.as_object();
+ auto key = entry.get(JS::PropertyKey { 0u });
+ auto entry_value = entry.get(JS::PropertyKey { 1u });
+ if (key.is_error() || entry_value.is_error())
+ continue;
+ roots.append(key.value());
+ roots.append(entry_value.value());
+ entries.append({ key.value(), entry_value.value() });
+ }
+ }
+
+ // 6. If serialized is not null, set field value of remote value to serialized.
+ remote_value.set("value"sv, serialize_as_a_mapping(entries, serialization_options, ownership_type));
+ }
+
+ // 7. Return remote value
+ return remote_value;
+}
+
+JsonValue serialize_as_a_remote_value(JS::Value value, SerializationOptions const& serialization_options, ResultOwnership ownership_type, HTML::EnvironmentSettingsObject& settings)
+{
+ Serializer serializer { .settings = settings, .depth = 0, .serialization_internal_map = {}, .serialized_objects = {}, .duplicated_markers = {}, .next_marker = 0, .internal_ids = {} };
+ auto remote_value = serializer.serialize_as_a_remote_value(value, serialization_options, ownership_type);
+ serializer.assign_internal_ids(remote_value);
+ return remote_value;
+}
+
+// https://tc39.es/ecma262/#sec-stringtobigint
+static Optional<::Crypto::SignedBigInteger> string_to_bigint(StringView string)
+{
+ // NB: StringIntegerLiteral allows the whitespace and line terminators that StrWhiteSpaceChar does around the
+ // literal, a sign only for a decimal literal, and an empty literal for 0n.
+ auto literal = string.trim_whitespace();
+ if (literal.is_empty())
+ return ::Crypto::SignedBigInteger { 0 };
+
+ u16 base = 10;
+ if (literal.length() > 2 && literal[0] == '0') {
+ auto prefix = to_ascii_lowercase(literal[1]);
+ if (prefix == 'x')
+ base = 16;
+ else if (prefix == 'o')
+ base = 8;
+ else if (prefix == 'b')
+ base = 2;
+ if (base != 10)
+ literal = literal.substring_view(2);
+ }
+
+ bool is_negative = false;
+ if (base == 10 && (literal.starts_with('-') || literal.starts_with('+'))) {
+ is_negative = literal[0] == '-';
+ literal = literal.substring_view(1);
+ }
+
+ if (literal.is_empty())
+ return {};
+ for (auto character : literal) {
+ if (!is_ascii_hex_digit(character) || parse_ascii_hex_digit(character) >= base)
+ return {};
+ }
+
+ auto result = ::Crypto::SignedBigInteger::from_base(base, literal);
+ if (result.is_error())
+ return {};
+ auto bigint = result.release_value();
+ if (is_negative)
+ bigint.negate();
+ return bigint;
+}
+
+// https://tc39.es/ecma262/#sec-timeclip
+static double time_clip(double time)
+{
+ // 1. If time is not finite, return NaN.
+ if (!isfinite(time))
+ return NAN;
+
+ // 2. If abs(ℝ(time)) > 8.64 × 10**15, return NaN.
+ if (fabs(time) > 8.64e15)
+ return NAN;
+
+ // 3. Return 𝔽(! ToIntegerOrInfinity(time)).
+ return trunc(time) + 0.0;
+}
+
+// https://w3c.github.io/webdriver-bidi/#deserialize-primitive-protocol-value
+static Optional<ErrorOr<JS::Value, Error>> deserialize_primitive_protocol_value(JS::VM& vm, JsonObject const& primitive_protocol_value)
+{
+ // 1. Let type be the value of the type field of primitive protocol value.
+ auto type = primitive_protocol_value.get_string("type"sv);
+ if (!type.has_value())
+ return {};
+
+ // 2. Let value be undefined.
+ // 3. If primitive protocol value has field value:
+ // 1. Let value be the value of the value field of primitive protocol value.
+ auto value = primitive_protocol_value.get("value"sv);
+
+ // 4. In the following list of conditions and associated steps, run the first set of steps for which the associated
+ // condition is true:
+ // -> type is the string "undefined"
+ if (*type == "undefined"sv) {
+ // Return success with data undefined.
+ return ErrorOr<JS::Value, Error> { JS::js_undefined() };
+ }
+
+ // -> type is the string "null"
+ if (*type == "null"sv) {
+ // Return success with data null.
+ return ErrorOr<JS::Value, Error> { JS::js_null() };
+ }
+
+ // -> type is the string "string"
+ if (*type == "string"sv) {
+ // Return success with data value.
+ if (!value.has_value() || !value->is_string())
+ return ErrorOr<JS::Value, Error> { invalid_argument("A string value must have a string value"sv) };
+ return ErrorOr<JS::Value, Error> { JS::PrimitiveString::create(vm, Utf16String::from_utf8(value->as_string())) };
+ }
+
+ // -> type is the string "number"
+ if (*type == "number"sv) {
+ if (!value.has_value())
+ return ErrorOr<JS::Value, Error> { invalid_argument("A number value must have a value"sv) };
+
+ // 1. If Type(value) is Number, return success with data value.
+ if (value->is_number())
+ return ErrorOr<JS::Value, Error> { JS::Value(value->get_number_with_precision_loss<double>().value()) };
+
+ // 2. Assert: Type(value) is String.
+ if (!value->is_string())
+ return ErrorOr<JS::Value, Error> { invalid_argument("A number value must be a number or a special number"sv) };
+ auto const& string = value->as_string();
+
+ // 3. If value is the string "NaN", return success with data NaN.
+ if (string == "NaN"sv)
+ return ErrorOr<JS::Value, Error> { JS::Value(NAN) };
+
+ // 4. Let number_result be StringToNumber(value).
+ // 5. If number_result is NaN, return error with error code invalid argument
+ // 6. Return success with data number_result.
+ // NB: The special numbers other than NaN are the strings StringToNumber gives a number for that JSON has no
+ // representation of.
+ if (string == "-0"sv)
+ return ErrorOr<JS::Value, Error> { JS::Value(-0.0) };
+ if (string == "Infinity"sv)
+ return ErrorOr<JS::Value, Error> { JS::Value(INFINITY) };
+ if (string == "-Infinity"sv)
+ return ErrorOr<JS::Value, Error> { JS::Value(-INFINITY) };
+ return ErrorOr<JS::Value, Error> { invalid_argument("A number value must be a number or a special number"sv) };
+ }
+
+ // -> type is the string "boolean"
+ if (*type == "boolean"sv) {
+ // Return success with data value.
+ if (!value.has_value() || !value->is_bool())
+ return ErrorOr<JS::Value, Error> { invalid_argument("A boolean value must have a boolean value"sv) };
+ return ErrorOr<JS::Value, Error> { JS::Value(value->as_bool()) };
+ }
+
+ // -> type is the string "bigint"
+ if (*type == "bigint"sv) {
+ // 1. Let bigint_result be StringToBigInt(value).
+ // 2. If bigint_result is undefined, return error with error code invalid argument
+ // 3. Return success with data bigint_result.
+ if (!value.has_value() || !value->is_string())
+ return ErrorOr<JS::Value, Error> { invalid_argument("A bigint value must have a string value"sv) };
+ auto bigint = string_to_bigint(value->as_string());
+ if (!bigint.has_value())
+ return ErrorOr<JS::Value, Error> { invalid_argument("A bigint value must be a valid BigInt"sv) };
+ return ErrorOr<JS::Value, Error> { JS::Value(JS::BigInt::create(vm, bigint.release_value())) };
+ }
+
+ return {};
+}
+
+// https://w3c.github.io/webdriver-bidi/#deserialize-shared-reference
+ErrorOr<JS::Value, Error> deserialize_shared_reference(JsonObject const& shared_reference, HTML::EnvironmentSettingsObject& settings)
+{
+ // 1. Assert shared reference matches the script.SharedReference production.
+ // 2. Let navigable be get the navigable with realm.
+ // https://w3c.github.io/webdriver-bidi/#get-the-navigable
+ auto* window = HTML::window_from_global_object(settings.global_object());
+ auto navigable = window ? window->associated_document().navigable() : nullptr;
+
+ // 3. If navigable is null, return error with error code no such node.
+ if (!navigable)
+ return Error::from_code(ErrorCode::NoSuchNode, "Realm is not the realm of a window"sv);
+
+ // 4. Let shared id be the value of the sharedId field of shared reference.
+ auto shared_id = shared_reference.get_string("sharedId"sv).value();
+
+ // 5. Let node be result of trying to get a node with session, navigable and shared id.
+ // NB: Getting a node looks it up in the node id map of navigable's browsing context group, so a node of another
+ // browsing context group is not found.
+ auto node = get_node(shared_id);
+ auto browsing_context_group_id = [](GC::Ptr<HTML::BrowsingContext> browsing_context) -> Optional<u64> {
+ if (!browsing_context || !browsing_context->top_level_browsing_context())
+ return {};
+ return browsing_context->top_level_browsing_context()->browsing_context_group_id();
+ };
+ if (node && browsing_context_group_id(node->document().browsing_context()) != browsing_context_group_id(navigable->active_browsing_context()))
+ node = nullptr;
+
+ // 6. If node is null, return error with error code no such node.
+ if (!node)
+ return Error::from_code(ErrorCode::NoSuchNode, "Node not found"sv);
+
+ // 7. Let environment settings be the environment settings object whose realm execution context's Realm component
+ // is realm.
+ // 8. If node's node document's origin is not same origin domain with environment settings's origin then return
+ // error with error code no such node.
+ if (!node->document().origin().is_same_origin_domain(settings.origin()))
+ return Error::from_code(ErrorCode::NoSuchNode, "Node is not accessible from the realm"sv);
+
+ // 9. Let realm global object be the global object of the realm.
+ // 10. If the realm global object is SandboxWindowProxy object, set node to the SandboxProxy wrapping node in the
+ // realm.
+
+ // 11. Return success with data node.
+ return BindingsGlue::wrap_node(settings, *node);
+}
+
+// https://w3c.github.io/webdriver-bidi/#deserialize-remote-object-reference
+static ErrorOr<JS::Value, Error> deserialize_remote_object_reference(JsonObject const& remote_object_reference, HTML::EnvironmentSettingsObject& settings)
+{
+ // 1. Let handle id be the value of the handle field of remote object reference.
+ auto handle_id = remote_object_reference.get_string("handle"sv).value();
+
+ // 2. Let handle map be realm's handle object map
+ // 3. If handle map does not contain handle id, then return error with error code no such handle.
+ auto handle_map = handle_object_maps().find(realm_id(settings));
+ if (handle_map == handle_object_maps().end())
+ return Error::from_code(ErrorCode::NoSuchHandle, "Handle not found"sv);
+ auto object = handle_map->value.find(handle_id);
+ if (object == handle_map->value.end())
+ return Error::from_code(ErrorCode::NoSuchHandle, "Handle not found"sv);
+
+ // 4. Return success with data handle map[handle id].
+ return object->value.first();
+}
+
+static ErrorOr<GC::RootVector<JS::Value>, Error> deserialize_value_list(JsonValue const* serialized_value_list, HTML::EnvironmentSettingsObject& settings)
+{
+ if (!serialized_value_list || !serialized_value_list->is_array())
+ return invalid_argument("Expected a list of local values"sv);
+
+ // https://w3c.github.io/webdriver-bidi/#deserialize-value-list
+ // 1. Let deserialized values be a new list.
+ GC::RootVector<JS::Value> deserialized_values;
+
+ // 2. For each serialized value in the serialized value list:
+ for (auto const& serialized_value : serialized_value_list->as_array().values()) {
+ // 1. Let deserialized value be result of trying to deserialize local value given serialized value, realm and
+ // session.
+ // 2. Append deserialized value to deserialized values;
+ deserialized_values.append(TRY(deserialize_local_value(serialized_value, settings)));
+ }
+
+ // 3. Return success with data deserialized values.
+ return deserialized_values;
+}
+
+// https://w3c.github.io/webdriver-bidi/#deserialize-key-value-list
+static ErrorOr<GC::ConservativeVector<Array<JS::Value, 2>>, Error> deserialize_key_value_list(JsonValue const* serialized_key_value_list, HTML::EnvironmentSettingsObject& settings, GC::RootVector<JS::Value>& roots)
+{
+ if (!serialized_key_value_list || !serialized_key_value_list->is_array())
+ return invalid_argument("Expected a list of key-value pairs"sv);
+
+ auto& vm = settings.global_object().vm();
+
+ // 1. Let deserialized key-value list be a new list.
+ GC::ConservativeVector<Array<JS::Value, 2>> deserialized_key_value_list;
+
+ // 2. For each serialized key-value in the serialized key-value list:
+ for (auto const& serialized_key_value : serialized_key_value_list->as_array().values()) {
+ // 1. If size of serialized key-value is not 2, return error with error code invalid argument.
+ if (!serialized_key_value.is_array() || serialized_key_value.as_array().size() != 2)
+ return invalid_argument("A key-value pair must be a list of 2 values"sv);
+
+ // 2. Let serialized key be serialized key-value[0].
+ auto const& serialized_key = serialized_key_value.as_array().at(0);
+
+ // 3. If serialized key is a string, let deserialized key be serialized key.
+ JS::Value deserialized_key;
+ if (serialized_key.is_string())
+ deserialized_key = JS::PrimitiveString::create(vm, Utf16String::from_utf8(serialized_key.as_string()));
+ // 4. Otherwise let deserialized key be result of trying to given deserialize local value with serialized key,
+ // realm and session.
+ else
+ deserialized_key = TRY(deserialize_local_value(serialized_key, settings));
+ roots.append(deserialized_key);
+
+ // 5. Let serialized value be serialized key-value[1].
+ auto const& serialized_value = serialized_key_value.as_array().at(1);
+
+ // 6. Let deserialized value be result of trying to deserialize local value given serialized value, realm and
+ // session.
+ auto deserialized_value = TRY(deserialize_local_value(serialized_value, settings));
+ roots.append(deserialized_value);
+
+ // 7. Append CreateArrayFromList(«deserialized key, deserialized value») to deserialized key-value list.
+ deserialized_key_value_list.append({ deserialized_key, deserialized_value });
+ }
+
+ // 3. Return success with data deserialized key-value list.
+ return deserialized_key_value_list;
+}
+
+// https://tc39.es/ecma262/#sec-date-time-string-format
+static Optional<double> parse_date_time_string(StringView string)
+{
+ GenericLexer lexer { string };
+
+ auto parse_digits = [&](size_t count) -> Optional<i64> {
+ i64 value = 0;
+ for (size_t i = 0; i < count; ++i) {
+ if (lexer.is_eof() || !is_ascii_digit(lexer.peek()))
+ return {};
+ value = value * 10 + (lexer.consume() - '0');
+ }
+ return value;
+ };
+
+ // YYYY, or ±YYYYYY for an expanded year.
+ i64 year = 0;
+ if (lexer.next_is('+') || lexer.next_is('-')) {
+ auto sign = lexer.consume() == '-' ? -1 : 1;
+ auto digits = parse_digits(6);
+ if (!digits.has_value() || (sign == -1 && *digits == 0))
+ return {};
+ year = sign * *digits;
+ } else {
+ auto digits = parse_digits(4);
+ if (!digits.has_value())
+ return {};
+ year = *digits;
+ }
+
+ i64 month = 1;
+ i64 day = 1;
+ if (lexer.consume_specific('-')) {
+ auto digits = parse_digits(2);
+ if (!digits.has_value() || *digits < 1 || *digits > 12)
+ return {};
+ month = *digits;
+ if (lexer.consume_specific('-')) {
+ digits = parse_digits(2);
+ if (!digits.has_value() || *digits < 1 || *digits > 31)
+ return {};
+ day = *digits;
+ }
+ }
+
+ i64 hour = 0;
+ i64 minute = 0;
+ i64 second = 0;
+ i64 millisecond = 0;
+ i64 offset_minutes = 0;
+ if (lexer.consume_specific('T')) {
+ auto digits = parse_digits(2);
+ if (!digits.has_value() || *digits > 24 || !lexer.consume_specific(':'))
+ return {};
+ hour = *digits;
+ digits = parse_digits(2);
+ if (!digits.has_value() || *digits > 59)
+ return {};
+ minute = *digits;
+ if (lexer.consume_specific(':')) {
+ digits = parse_digits(2);
+ if (!digits.has_value() || *digits > 59)
+ return {};
+ second = *digits;
+ if (lexer.consume_specific('.')) {
+ digits = parse_digits(3);
+ if (!digits.has_value())
+ return {};
+ millisecond = *digits;
+ }
+ }
+ if (hour == 24 && (minute != 0 || second != 0 || millisecond != 0))
+ return {};
+
+ // FIXME: A date-time form without a UTC offset is a local time, which this treats as UTC.
+ if (lexer.consume_specific('Z')) {
+ } else if (lexer.next_is('+') || lexer.next_is('-')) {
+ auto sign = lexer.consume() == '-' ? -1 : 1;
+ auto offset_hours = parse_digits(2);
+ if (!offset_hours.has_value() || *offset_hours > 23 || !lexer.consume_specific(':'))
+ return {};
+ auto offset_minutes_part = parse_digits(2);
+ if (!offset_minutes_part.has_value() || *offset_minutes_part > 59)
+ return {};
+ offset_minutes = sign * (*offset_hours * 60 + *offset_minutes_part);
+ }
+ }
+
+ if (!lexer.is_eof())
+ return {};
+
+ auto date = JS::make_day(static_cast<double>(year), static_cast<double>(month - 1), static_cast<double>(day));
+ auto time = JS::make_time(static_cast<double>(hour), static_cast<double>(minute), static_cast<double>(second), static_cast<double>(millisecond));
+ return JS::make_date(date, time) - static_cast<double>(offset_minutes) * 60'000;
+}
+
+// https://w3c.github.io/webdriver-bidi/#deserialize-local-value
+ErrorOr<JS::Value, Error> deserialize_local_value(JsonValue const& local_protocol_value_json, HTML::EnvironmentSettingsObject& settings)
+{
+ auto& vm = settings.global_object().vm();
+
+ if (!local_protocol_value_json.is_object())
+ return invalid_argument("A local value must be an object"sv);
+ auto const& local_protocol_value = local_protocol_value_json.as_object();
+
+ // 1. If local protocol value matches the script.RemoteReference production, return deserialize remote reference of
+ // given local protocol value, realm and session.
+ // https://w3c.github.io/webdriver-bidi/#deserialize-remote-reference
+ // NB: If the provided reference has both handle and sharedId, the algorithm will ignore handle and respect only
+ // sharedId.
+ if (auto shared_id = local_protocol_value.get("sharedId"sv); shared_id.has_value()) {
+ if (!shared_id->is_string())
+ return invalid_argument("sharedId must be a string"sv);
+ if (auto handle = local_protocol_value.get("handle"sv); handle.has_value() && !handle->is_string())
+ return invalid_argument("handle must be a string"sv);
+ return deserialize_shared_reference(local_protocol_value, settings);
+ }
+ if (auto handle = local_protocol_value.get("handle"sv); handle.has_value()) {
+ if (!handle->is_string())
+ return invalid_argument("handle must be a string"sv);
+ return deserialize_remote_object_reference(local_protocol_value, settings);
+ }
+
+ // 2. If local protocol value matches the script.PrimitiveProtocolValue production, return deserialize primitive
+ // protocol value with local protocol value.
+ if (auto primitive = deserialize_primitive_protocol_value(vm, local_protocol_value); primitive.has_value())
+ return primitive.release_value();
+
+ // 4. Let type be the value of the type field of local protocol value or undefined if no such a field.
+ auto type = local_protocol_value.get_string("type"sv);
+ if (!type.has_value())
+ return invalid_argument("A local value must have a type"sv);
+
+ // 3. If local protocol value matches the script.ChannelValue production, return create a channel with session, realm
+ // and local protocol value.
+ if (*type == "channel"sv) {
+ // script.ChannelValue = {
+ // type: "channel",
+ // value: script.ChannelProperties,
+ // }
+ // script.ChannelProperties = {
+ // channel: script.Channel,
+ // ? serializationOptions: script.SerializationOptions,
+ // ? ownership: script.ResultOwnership,
+ // }
+ auto properties = local_protocol_value.get_object("value"sv);
+ if (!properties.has_value() || !properties->get_string("channel"sv).has_value())
+ return invalid_argument("A channel value must have channel properties with a channel"sv);
+ if (auto options = properties->get("serializationOptions"sv); options.has_value())
+ TRY(parse_serialization_options(*options));
+ if (auto ownership = properties->get("ownership"sv); ownership.has_value())
+ TRY(parse_result_ownership(*ownership));
+ return create_a_channel(settings, local_protocol_value);
+ }
+
+ // 5. Let value be the value of the value field of local protocol value or undefined if no such a field.
+ auto value = local_protocol_value.get("value"sv);
+ auto const* value_pointer = value.has_value() ? &value.value() : nullptr;
+
+ // 6. In the following list of conditions and associated steps, run the first set of steps for which the associated
+ // condition is true:
+ // -> type is the string "array"
+ if (*type == "array"sv) {
+ // 1. Let deserialized value list be a result of trying to deserialize value list given value, realm and session.
+ auto deserialized_value_list = TRY(deserialize_value_list(value_pointer, settings));
+
+ // 2. Return success with data CreateArrayFromList(deserialized value list).
+ return BindingsGlue::create_array(settings, deserialized_value_list.span());
+ }
+
+ // -> type is the string "date"
+ if (*type == "date"sv) {
+ // 1. If value does not match Date Time String Format, return error with error code invalid argument.
+ if (!value_pointer || !value_pointer->is_string())
+ return invalid_argument("A date value must be a string"sv);
+ auto date_value = parse_date_time_string(value_pointer->as_string());
+ if (!date_value.has_value())
+ return invalid_argument("A date value must match the Date Time String Format"sv);
+
+ // 2. Let date result be Construct(Date, value).
+ // 3. Assert: date result is not an abrupt completion.
+ // 4. Return success with data date result.
+ return BindingsGlue::create_date(settings, time_clip(*date_value));
+ }
+
+ // -> type is the string "map"
+ if (*type == "map"sv) {
+ // 1. Let deserialized key-value list be a result of trying to deserialize key-value list with value, realm and
+ // session.
+ GC::RootVector<JS::Value> roots;
+ auto deserialized_key_value_list = TRY(deserialize_key_value_list(value_pointer, settings, roots));
+
+ // 2. Let iterable be CreateArrayFromList(deserialized key-value list)
+ // 3. Return success with data Map(iterable).
+ auto map = BindingsGlue::create_map(settings);
+ for (auto const& entry : deserialized_key_value_list)
+ map->map_set(entry[0], entry[1]);
+ return map;
+ }
+
+ // -> type is the string "object"
+ if (*type == "object"sv) {
+ // 1. Let deserialized key-value list be a result of trying to deserialize key-value list with value, realm and
+ // session.
+ GC::RootVector<JS::Value> roots;
+ auto deserialized_key_value_list = TRY(deserialize_key_value_list(value_pointer, settings, roots));
+
+ // 2. Let iterable be CreateArrayFromList(deserialized key-value list)
+ // 3. Return success with data Object.fromEntries(iterable).
+ auto object = BindingsGlue::create_object(settings);
+ for (auto const& entry : deserialized_key_value_list) {
+ auto property_key = JS::PropertyKey::from_value(vm, entry[0]);
+ if (property_key.is_error())
+ return invalid_argument("An object key must be a property key"sv);
+ MUST(object->create_data_property_or_throw(property_key.release_value(), entry[1]));
+ }
+ return object;
+ }
+
+ // -> type is the string "regexp"
+ if (*type == "regexp"sv) {
+ if (!value_pointer || !value_pointer->is_object())
+ return invalid_argument("A regexp value must be an object"sv);
+
+ // 1. Let pattern be the value of the pattern field of local protocol value.
+ auto pattern = value_pointer->as_object().get_string("pattern"sv);
+ if (!pattern.has_value())
+ return invalid_argument("A regexp value must have a string pattern"sv);
+
+ // 2. Let flags be the value of the flags field of local protocol value or undefined if no such a field.
+ JS::Value flags = JS::js_undefined();
+ if (auto flags_value = value_pointer->as_object().get("flags"sv); flags_value.has_value()) {
+ if (!flags_value->is_string())
+ return invalid_argument("The flags of a regexp value must be a string"sv);
+ flags = JS::PrimitiveString::create(vm, Utf16String::from_utf8(flags_value->as_string()));
+ }
+
+ // 3. Let regex_result be Regexp(pattern, flags). If this throws exception, return error with error code invalid
+ // argument.
+ auto regex_result = JS::regexp_create(vm, JS::PrimitiveString::create(vm, Utf16String::from_utf8(*pattern)), flags);
+ if (regex_result.is_error())
+ return invalid_argument("The regexp value is not a valid regular expression"sv);
+
+ // 4. Return success with data regex_result.
+ return JS::Value { regex_result.value() };
+ }
+
+ // -> type is the string "set"
+ if (*type == "set"sv) {
+ // 1. Let deserialized value list be a result of trying to deserialize value list given value, realm and session.
+ auto deserialized_value_list = TRY(deserialize_value_list(value_pointer, settings));
+
+ // 2. Let iterable be CreateArrayFromList(deserialized key-value list)
+ // 3. Return success with data Set object(iterable).
+ auto set = BindingsGlue::create_set(settings);
+ for (auto item : deserialized_value_list)
+ set->set_add(item);
+ return set;
+ }
+
+ // -> otherwise
+ // Return error with error code invalid argument.
+ return invalid_argument("Unknown local value type"sv);
+}
+
+static JsonObject stack_frame(Utf16View function_name, Utf16View url, JS::Position position)
+{
+ // script.StackFrame = {
+ // columnNumber: js-uint,
+ // functionName: text,
+ // lineNumber: js-uint,
+ // url: text,
+ // }
+ // NB: The line and column numbers of a stack frame are zero-based, while those the engine keeps are one-based.
+ JsonObject frame_info;
+ frame_info.set("columnNumber"sv, position.column > 0 ? position.column - 1 : 0);
+ frame_info.set("functionName"sv, to_utf8(function_name));
+ frame_info.set("lineNumber"sv, position.line > 0 ? position.line - 1 : 0);
+ frame_info.set("url"sv, to_utf8(url));
+ return frame_info;
+}
+
+// https://w3c.github.io/webdriver-bidi/#construct-a-stack-trace
+static JsonObject construct_a_stack_trace(Vector<JS::TracebackFrame, 32> const& stack)
+{
+ // 1. Let call frames be a new list.
+ JsonArray call_frames;
+
+ // 2. For each stack frame frame in stack, starting from the most recently executed frame, run the following steps:
+ for (auto const& frame : stack) {
+ // 1. Let url be the result of running the URL serializer, given the URL of frame's script url.
+ // 2. Let frame info be a new map matching the script.StackFrame production, with the url field set to url, the
+ // functionName field set to frame's function, the lineNumber field set to frame's line number and the
+ // columnNumber field set to frame's column number.
+ auto const& source_range = frame.source_range();
+
+ // NB: A frame of native code has no script.
+ if (source_range.filename().is_empty())
+ continue;
+
+ // 3. Append frame info to call frames.
+ call_frames.must_append(stack_frame(frame.function_name, source_range.filename(), source_range.start));
+ }
+
+ // 4. Let stack trace be a new map matching the script.StackTrace production, with the callFrames property set to
+ // call frames.
+ JsonObject stack_trace;
+ stack_trace.set("callFrames"sv, move(call_frames));
+
+ // 5. Return stack trace.
+ return stack_trace;
+}
+
+// https://w3c.github.io/webdriver-bidi/#stack-trace-for-an-exception
+JsonObject stack_trace_for_an_exception(JS::Value exception)
+{
+ // 1. If exception is a value that has been thrown as an exception, let record be the Completion Record created to
+ // throw exception. Otherwise let record be exception.
+ // 2. Let stack be the list of stack frames corresponding to execution at the point record was created.
+ // NB: An error keeps the stack it was created on.
+ Vector<JS::TracebackFrame, 32> stack;
+ if (exception.is_object()) {
+ if (auto const* error_data = exception.as_object().error_data())
+ stack = error_data->traceback();
+ }
+
+ // 3. Return construct a stack trace given stack.
+ return construct_a_stack_trace(stack);
+}
+
+// https://w3c.github.io/webdriver-bidi/#current-stack-trace
+JsonObject current_stack_trace(JS::VM& vm)
+{
+ // The current stack trace is the result of construct a stack trace given a list of stack frames representing the
+ // callstack of the running execution context.
+ return construct_a_stack_trace(JS::ErrorDataCell::capture(vm)->traceback());
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-exception-details
+String textual_description_of_an_exception(HTML::EnvironmentSettingsObject& settings, JS::Value exception)
+{
+ if (exception.is_object() && exception.as_object().has_error_data()) {
+ auto& object = exception.as_object();
+ auto& vm = settings.global_object().vm();
+ auto name = object.get_without_side_effects(vm.names.name);
+ auto message = object.get_without_side_effects(vm.names.message);
+ auto name_string = name.is_string() ? to_utf8(name.as_string().utf16_string_view()) : "Error"_string;
+ auto message_string = message.is_string() ? to_utf8(message.as_string().utf16_string_view()) : String {};
+ return message_string.is_empty() ? name_string : MUST(String::formatted("{}: {}", name_string, message_string));
+ }
+ return to_utf8(exception.to_utf16_string_without_side_effects());
+}
+
+JsonObject get_exception_details(HTML::EnvironmentSettingsObject& settings, JS::Value exception, ResultOwnership ownership_type)
+{
+ // 1. Assert: record.[[Type]] is throw.
+
+ // 2. Let text be an implementation-defined textual description of the error represented by record.
+ auto text = textual_description_of_an_exception(settings, exception);
+
+ // 3. Let serialization options be a map matching the script.SerializationOptions production with the fields set to
+ // their default values.
+ SerializationOptions serialization_options;
+
+ // 4. Let exception be the result of serialize as a remote value with record.[[Value]], serialization options,
+ // ownership type, a new map as serialization internal map, realm and session.
+ auto serialized_exception = serialize_as_a_remote_value(exception, serialization_options, ownership_type, settings);
+
+ // 5. Let stack trace be the stack trace for an exception given record.
+ auto stack_trace = stack_trace_for_an_exception(exception);
+
+ // 6. If stack trace has size of 1 or greater, let line number be value of the lineNumber field in stack trace[0], and
+ // let column number be the value of the columnNumber field stack trace[0]. Otherwise let line number and column
+ // number be 0.
+ JsonValue line_number = 0;
+ JsonValue column_number = 0;
+ if (auto call_frames = stack_trace.get_array("callFrames"sv); call_frames.has_value() && call_frames->size() > 0) {
+ auto const& first_frame = call_frames->at(0).as_object();
+ line_number = *first_frame.get("lineNumber"sv);
+ column_number = *first_frame.get("columnNumber"sv);
+ }
+
+ // 7. Let exception details be a map matching the script.ExceptionDetails production, with the text field set to
+ // text, the exception field set to exception, the lineNumber field set to line number, the columnNumber field set
+ // to column number, and the stackTrace field set to stack trace.
+ JsonObject exception_details;
+ exception_details.set("columnNumber"sv, move(column_number));
+ exception_details.set("exception"sv, move(serialized_exception));
+ exception_details.set("lineNumber"sv, move(line_number));
+ exception_details.set("stackTrace"sv, move(stack_trace));
+ exception_details.set("text"sv, move(text));
+
+ // 8. Return exception details.
+ return exception_details;
+}
+
+}
diff --git a/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.h b/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.h
new file mode 100644
index 00000000000..9b42395b373
--- /dev/null
+++ b/Libraries/LibWeb/WebDriver/BiDi/RemoteValue.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/HashMap.h>
+#include <AK/JsonObject.h>
+#include <AK/JsonValue.h>
+#include <AK/Optional.h>
+#include <AK/String.h>
+#include <LibGC/Ptr.h>
+#include <LibJS/Forward.h>
+#include <LibJS/Runtime/Value.h>
+#include <LibWeb/Forward.h>
+#include <LibWebCommon/WebDriver/BiDi.h>
+#include <LibWebCommon/WebDriver/Error.h>
+
+namespace Web::WebDriver::BiDi {
+
+// https://w3c.github.io/webdriver-bidi/#type-script-ResultOwnership
+enum class ResultOwnership : u8 {
+ Root,
+ None,
+};
+
+ErrorOr<ResultOwnership, Error> parse_result_ownership(JsonValue const&);
+
+// https://w3c.github.io/webdriver-bidi/#realm-id
+String realm_id(HTML::EnvironmentSettingsObject&);
+
+// The realm whose id is realm id, if the document of the given navigable has it.
+HTML::EnvironmentSettingsObject* settings_with_realm_id(HTML::Navigable&, StringView realm_id);
+
+// https://w3c.github.io/webdriver-bidi/#handle-object-map
+void clear_handle_object_map(HTML::EnvironmentSettingsObject&);
+// NB: The handles of a session that ended name nothing.
+void clear_all_handle_object_maps();
+bool remove_handle(HTML::EnvironmentSettingsObject&, StringView handle_id);
+
+// https://w3c.github.io/webdriver-bidi/#serialize-as-a-remote-value
+// NB: The serialization internal map is internal to the serialization, which takes a value and returns its remote value.
+JsonValue serialize_as_a_remote_value(JS::Value, SerializationOptions const&, ResultOwnership, HTML::EnvironmentSettingsObject&);
+
+// https://w3c.github.io/webdriver-bidi/#deserialize-shared-reference
+ErrorOr<JS::Value, Error> deserialize_shared_reference(JsonObject const& shared_reference, HTML::EnvironmentSettingsObject&);
+
+// https://w3c.github.io/webdriver-bidi/#deserialize-local-value
+ErrorOr<JS::Value, Error> deserialize_local_value(JsonValue const& local_protocol_value, HTML::EnvironmentSettingsObject&);
+
+// https://w3c.github.io/webdriver-bidi/#stack-trace-for-an-exception
+JsonObject stack_trace_for_an_exception(JS::Value exception);
+
+// https://w3c.github.io/webdriver-bidi/#current-stack-trace
+JsonObject current_stack_trace(JS::VM&);
+
+// NB: The implementation-defined textual description of an exception that get the exception details gives.
+String textual_description_of_an_exception(HTML::EnvironmentSettingsObject&, JS::Value exception);
+
+// https://w3c.github.io/webdriver-bidi/#get-exception-details
+JsonObject get_exception_details(HTML::EnvironmentSettingsObject&, JS::Value exception, ResultOwnership);
+
+}
diff --git a/Libraries/LibWeb/WebDriver/BiDi/Script.cpp b/Libraries/LibWeb/WebDriver/BiDi/Script.cpp
new file mode 100644
index 00000000000..0636efae84e
--- /dev/null
+++ b/Libraries/LibWeb/WebDriver/BiDi/Script.cpp
@@ -0,0 +1,860 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/HashMap.h>
+#include <AK/JsonArray.h>
+#include <AK/RefCounted.h>
+#include <LibGC/ConservativeVector.h>
+#include <LibGC/Function.h>
+#include <LibGC/Heap.h>
+#include <LibGC/Root.h>
+#include <LibJS/Runtime/AbstractOperations.h>
+#include <LibJS/Runtime/Error.h>
+#include <LibJS/Runtime/NativeFunction.h>
+#include <LibJS/Runtime/Promise.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/HTML/LocalNavigable.h>
+#include <LibWeb/HTML/Navigable.h>
+#include <LibWeb/HTML/Scripting/ClassicScript.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/ExceptionReporter.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/HTML/Window.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
+#include <LibWeb/WebDriver/BiDi/BindingsGlue.h>
+#include <LibWeb/WebDriver/BiDi/RemoteValue.h>
+#include <LibWeb/WebDriver/BiDi/Script.h>
+#include <LibWeb/WebIDL/Promise.h>
+
+namespace Web::WebDriver::BiDi {
+
+// https://w3c.github.io/webdriver-bidi/#default-user-context
+// FIXME: Support user contexts other than the default user context.
+static constexpr auto DEFAULT_USER_CONTEXT_ID = "default"sv;
+
+static Error invalid_argument(StringView message)
+{
+ return Error::from_code(ErrorCode::InvalidArgument, message);
+}
+
+static Error no_such_frame()
+{
+ return Error::from_code(ErrorCode::NoSuchFrame, "Realm not found"sv);
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-the-realm-info
+Optional<JsonObject> get_the_realm_info(HTML::EnvironmentSettingsObject& environment_settings)
+{
+ // 1. Let realm be environment settings' realm execution context's Realm component.
+
+ // 2. Let realm id be the realm id for realm.
+ auto id = realm_id(environment_settings);
+
+ // 3. Let origin be the serialization of an origin given environment settings's origin.
+ auto origin = environment_settings.origin().serialize();
+
+ // 4. Let global object be the global object specified by environment settings
+ auto& global_object = environment_settings.global_object();
+
+ // 5. Run the steps under the first matching condition:
+ // -> global object is a Window object
+ if (auto* window = HTML::window_from_global_object(global_object)) {
+ // 1. Let document be environment settings' relevant global object's associated Document.
+ auto& document = window->associated_document();
+
+ // 2. Let navigable be document's node navigable.
+ auto navigable = document.navigable();
+
+ // 3. If navigable is null, return null.
+ if (!navigable)
+ return {};
+
+ // 4. Let navigable id be the navigable id for navigable.
+ // 5. Let user context id be the user context id of navigable's associated user context
+ // 6. Let realm info be a map matching the script.WindowRealmInfo production, with the realm field set to realm
+ // id, the origin field set to origin, the context field set to navigable id and the userContext field set to
+ // user context id.
+ JsonObject realm_info;
+ realm_info.set("realm"sv, move(id));
+ realm_info.set("origin"sv, move(origin));
+ realm_info.set("type"sv, "window"sv);
+ realm_info.set("context"sv, navigable_id(*navigable));
+ realm_info.set("userContext"sv, DEFAULT_USER_CONTEXT_ID);
+ return realm_info;
+ }
+
+ // FIXME: -> global object is SandboxWindowProxy object
+ // FIXME: -> global object is a WorkerGlobalScope or WorkletGlobalScope object
+
+ // -> Otherwise:
+ // 1. Let realm info be null.
+ return {};
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-the-source
+JsonObject get_the_source(HTML::EnvironmentSettingsObject& environment_settings)
+{
+ // 1. Let realm be the realm id for source realm.
+ auto settings = realm_id(environment_settings);
+
+ // 2. Let environment settings be the environment settings object whose realm execution context's Realm component
+ // is source realm.
+
+ // 3. If environment settings has a associated Document:
+ // 1. Let document be environment settings’ associated Document.
+ // 2. Let navigable be document’s node navigable.
+ // 3. Let navigable id be the navigable id for navigable if navigable is not null.
+ // 4. Let user context id be the user context id of navigable's associated user context.
+ // Otherwise let navigable be null.
+ GC::Ptr<HTML::Navigable> navigable;
+ if (auto* window = HTML::window_from_global_object(environment_settings.global_object()))
+ navigable = window->associated_document().navigable();
+
+ // 4. Let source be a map matching the script.Source production with the realm field set to realm, the context field
+ // set to navigable id if navigable is not null, or unset otherwise, and the userContext field set to user context
+ // id if |navigable is not null, or unset otherwise.
+ JsonObject source;
+ source.set("realm"sv, move(settings));
+ if (navigable) {
+ source.set("context"sv, navigable_id(*navigable));
+ source.set("userContext"sv, DEFAULT_USER_CONTEXT_ID);
+ }
+
+ // 5. Return source.
+ return source;
+}
+
+// https://w3c.github.io/webdriver-bidi/#create-a-channel
+JS::Value create_a_channel(HTML::EnvironmentSettingsObject& settings, JsonObject const& protocol_value)
+{
+ // 1. Let channel properties be protocol value["value"].
+ auto channel_properties = protocol_value.get_object("value"sv).value_or({});
+
+ // 2. Let steps be the following steps given the argument message:
+ auto steps = [channel_properties = move(channel_properties)](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
+ auto message = vm.argument(0);
+
+ // 1. Let current realm be the current Realm Record.
+ auto& current_settings = HTML::current_settings_object();
+
+ // 2. Emit a script message with session, current realm, channel properties and message.
+ // https://w3c.github.io/webdriver-bidi/#emit-a-script-message
+ if (!is_active() || !is_event_enabled("script.message"sv))
+ return JS::js_undefined();
+
+ // 1. Let environment settings be the environment settings object whose realm execution context's Realm
+ // component is realm.
+ auto& environment_settings = current_settings;
+
+ // 2. Let related navigables be the result of get related navigables given environment settings.
+ auto* window = HTML::window_from_global_object(environment_settings.global_object());
+ auto navigable = window ? window->associated_document().navigable() : nullptr;
+ if (!navigable)
+ return JS::js_undefined();
+
+ // 3. If event is enabled given session, "script.message" and related navigables:
+ // NB: The browser process emits the event if some subscription enables it.
+
+ // 1. If channel properties contains "serializationOptions", let serialization options be the value of the
+ // serializationOptions field of channel properties. Otherwise let serialization options be a map matching
+ // the script.SerializationOptions production with the fields set to their default values.
+ SerializationOptions serialization_options;
+ if (auto options = channel_properties.get("serializationOptions"sv); options.has_value()) {
+ if (auto parsed = parse_serialization_options(*options); !parsed.is_error())
+ serialization_options = parsed.release_value();
+ }
+
+ // 2. Let if channel properties contains "ownership", let ownership type be channel properties["ownership"].
+ // Otherwise let ownership type be "none".
+ auto ownership_type = ResultOwnership::None;
+ if (auto ownership = channel_properties.get("ownership"sv); ownership.has_value()) {
+ if (auto parsed = parse_result_ownership(*ownership); !parsed.is_error())
+ ownership_type = parsed.release_value();
+ }
+
+ // 3. Let data be the result of serialize as a remote value given message, serialization options, ownership type,
+ // a new map as serialization internal map and realm.
+ auto data = serialize_as_a_remote_value(message, serialization_options, ownership_type, current_settings);
+
+ // 4. Let source be the get the source with realm.
+ auto source = get_the_source(current_settings);
+
+ // 5. Let params be a map matching the script.MessageParameters production, with the channel field set to
+ // channel properties["channel"], the data field set to data, and the source field set to source.
+ JsonObject params;
+ params.set("channel"sv, channel_properties.get_string("channel"sv).value_or({}));
+ params.set("data"sv, move(data));
+ params.set("source"sv, move(source));
+
+ // 6. Let body be a map matching the script.Message production, with the params field set to params.
+ // 7. Emit an event with session and body.
+ emit_event(*navigable, "script.message"_string, move(params));
+ return JS::js_undefined();
+ };
+
+ // 3. Return CreateBuiltinFunction(steps, 1, "", « », realm).
+ return BindingsGlue::create_channel_function(settings, move(steps));
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-a-realm-from-a-target
+// NB: The browser process routes the command to the process hosting the navigable of the target, which is the given
+// navigable.
+static ErrorOr<HTML::EnvironmentSettingsObject*, Error> get_a_realm_from_a_target(HTML::Navigable& navigable, JsonObject const& params)
+{
+ auto target_value = params.get("target"sv);
+ if (!target_value.has_value() || !target_value->is_object())
+ return invalid_argument("Parameter 'target' must be an object"sv);
+ auto const& target = target_value->as_object();
+
+ // 1. If target matches the script.ContextTarget production:
+ if (target.has("context"sv)) {
+ // 1. Let sandbox be null.
+ // 2. If target contains "sandbox", set sandbox to target["sandbox"].
+ Optional<String> sandbox;
+ if (auto sandbox_value = target.get("sandbox"sv); sandbox_value.has_value()) {
+ if (!sandbox_value->is_string())
+ return invalid_argument("Parameter 'sandbox' must be a string"sv);
+ sandbox = sandbox_value->as_string();
+ }
+
+ // 3. Let realm be get a realm from a navigable with target["context"] and sandbox.
+ // https://w3c.github.io/webdriver-bidi/#get-a-realm-from-a-navigable
+ // 1. Let navigable be the result of trying to get a navigable with navigable id.
+ auto* local_navigable = as_if<HTML::LocalNavigable>(navigable);
+ if (!local_navigable || !local_navigable->active_document())
+ return Error::from_code(ErrorCode::NoSuchFrame, "Browsing context not found"sv);
+
+ // 2. If sandbox is null or is an empty string:
+ if (!sandbox.has_value() || sandbox->is_empty()) {
+ // 1. Let document be navigable's active document.
+ // 2. Let environment settings be the environment settings object whose relevant global object's associated
+ // Document is document.
+ // 3. Let realm be environment settings' realm execution context's Realm component.
+ return &local_navigable->active_document()->relevant_settings_object();
+ }
+
+ // 3. Otherwise: let realm be result of trying to get or create a sandbox realm given sandbox and navigable.
+ // FIXME: Implement sandbox realms.
+ return Error::from_code(ErrorCode::UnsupportedOperation, "Sandbox realms are not supported"sv);
+ }
+
+ // 2. Otherwise:
+ if (auto id = target.get_string("realm"sv); id.has_value()) {
+ // 1. Assert: target matches the script.RealmTarget production.
+ // 2. Let realm id be the value of the realm field of target.
+ // 3. Let realm be get a realm given realm id.
+ // https://w3c.github.io/webdriver-bidi/#get-a-realm
+ // 2. If there is no realm with id realm id return error with error code no such frame
+ auto* settings = settings_with_realm_id(navigable, *id);
+ if (!settings)
+ return no_such_frame();
+
+ // 3. Let realm be the realm with id realm id.
+ // 4. Return success with data realm
+ return settings;
+ }
+
+ return invalid_argument("Parameter 'target' must be a context or realm target"sv);
+}
+
+static ErrorOr<bool, Error> get_bool(JsonObject const& params, StringView name)
+{
+ auto value = params.get(name);
+ if (!value.has_value() || !value->is_bool())
+ return invalid_argument(MUST(String::formatted("Parameter '{}' must be a boolean", name)));
+ return value->as_bool();
+}
+
+static ErrorOr<bool, Error> get_optional_bool(JsonObject const& params, StringView name, bool default_value)
+{
+ if (!params.has(name))
+ return default_value;
+ return get_bool(params, name);
+}
+
+static ErrorOr<String, Error> get_string(JsonObject const& params, StringView name)
+{
+ auto value = params.get(name);
+ if (!value.has_value() || !value->is_string())
+ return invalid_argument(MUST(String::formatted("Parameter '{}' must be a string", name)));
+ return value->as_string();
+}
+
+static ErrorOr<SerializationOptions, Error> get_serialization_options(JsonObject const& params)
+{
+ // Let serialization options be the value of the serializationOptions field of command parameters, if present, or
+ // otherwise a map matching the script.SerializationOptions production with the fields set to their default values.
+ if (auto value = params.get("serializationOptions"sv); value.has_value())
+ return parse_serialization_options(*value);
+ return SerializationOptions {};
+}
+
+static ErrorOr<ResultOwnership, Error> get_result_ownership(JsonObject const& params)
+{
+ // Let result ownership be the value of the resultOwnership field of command parameters, if present, or none
+ // otherwise.
+ if (auto value = params.get("resultOwnership"sv); value.has_value())
+ return parse_result_ownership(*value);
+ return ResultOwnership::None;
+}
+
+// https://html.spec.whatwg.org/multipage/interaction.html#activation-notification
+static void run_activation_notification_steps(HTML::EnvironmentSettingsObject& settings)
+{
+ // AD-HOC: Notify the window of the realm, the way a user interaction with its document does.
+ auto& environment_settings = settings;
+ if (auto* window = HTML::window_from_global_object(environment_settings.global_object()))
+ window->notify_about_user_activation();
+}
+
+static JsonObject evaluation_result_exception(HTML::EnvironmentSettingsObject& settings, JS::Value exception, ResultOwnership result_ownership)
+{
+ // 1. Let exception details be the result of get exception details given realm, evaluation status, result ownership
+ // and session.
+ // 2. Return a new map matching the script.EvaluationResultException production, with the realm field set to realm
+ // id, and the exceptionDetails field set to exception details.
+ JsonObject result;
+ result.set("type"sv, "exception"sv);
+ result.set("exceptionDetails"sv, get_exception_details(settings, exception, result_ownership));
+ result.set("realm"sv, realm_id(settings));
+ return result;
+}
+
+static JsonObject evaluation_result_success(HTML::EnvironmentSettingsObject& settings, JS::Value value, SerializationOptions const& serialization_options, ResultOwnership result_ownership)
+{
+ // 1. Let result be the result of serialize as a remote value with evaluation status.[[Value]], serialization
+ // options, result ownership, a new map as serialization internal map, realm and session.
+ auto result = serialize_as_a_remote_value(value, serialization_options, result_ownership, settings);
+
+ // 2. Return a new map matching the script.EvaluationResultSuccess production, with the realm field set to realm id,
+ // and the result field set to result.
+ JsonObject body;
+ body.set("type"sv, "success"sv);
+ body.set("result"sv, move(result));
+ body.set("realm"sv, realm_id(settings));
+ return body;
+}
+
+namespace {
+
+// NB: The session keeps an awaited promise and its evaluation alive until it settles or its environment is destroyed.
+struct PendingEvaluation : RefCounted<PendingEvaluation> {
+ AK_ALLOC_WITH_KMALLOC;
+
+ String environment_id;
+ GC::Root<WebIDL::Promise> promise;
+ OnCommandComplete on_complete;
+ SerializationOptions serialization_options;
+ ResultOwnership result_ownership { ResultOwnership::None };
+
+ void complete(Response);
+
+ void fail()
+ {
+ complete(Error::from_code(ErrorCode::UnknownError, "The realm was destroyed while awaiting the promise"sv));
+ }
+};
+
+}
+
+static HashMap<String, Vector<NonnullRefPtr<PendingEvaluation>>>& pending_evaluations()
+{
+ static auto& evaluations = *new HashMap<String, Vector<NonnullRefPtr<PendingEvaluation>>>;
+ return evaluations;
+}
+
+void PendingEvaluation::complete(Response response)
+{
+ if (!on_complete)
+ return;
+
+ // NB: Completion may run more script or end the session. Remove this evaluation before calling out.
+ if (auto evaluations = pending_evaluations().find(environment_id); evaluations != pending_evaluations().end()) {
+ evaluations->value.remove_all_matching([this](auto const& evaluation) { return evaluation.ptr() == this; });
+ if (evaluations->value.is_empty())
+ pending_evaluations().remove(evaluations);
+ }
+ promise = {};
+ auto callback = move(on_complete);
+ callback(move(response));
+}
+
+void fail_pending_evaluations(HTML::EnvironmentSettingsObject& settings)
+{
+ auto evaluations = pending_evaluations().take(realm_id(settings));
+ if (!evaluations.has_value())
+ return;
+ for (auto& evaluation : *evaluations)
+ evaluation->fail();
+}
+
+void fail_all_pending_evaluations()
+{
+ auto evaluations = move(pending_evaluations());
+ pending_evaluations().clear();
+ for (auto& entry : evaluations) {
+ for (auto& evaluation : entry.value)
+ evaluation->complete(Error::from_code(ErrorCode::UnknownError, "The session ended while awaiting the promise"sv));
+ }
+}
+
+// NB: The steps of evaluate and callFunction once their evaluation status is known: they await a promise if asked to,
+// and complete with the evaluation result.
+static void complete_evaluation(HTML::EnvironmentSettingsObject& settings, JS::Completion evaluation_status, bool await_promise, SerializationOptions serialization_options, ResultOwnership result_ownership, OnCommandComplete on_complete)
+{
+ // If evaluation status.[[Type]] is normal, await promise is true, and IsPromise(evaluation status.[[Value]]):
+ if (!evaluation_status.is_abrupt() && await_promise && evaluation_status.value().is_object() && is<JS::Promise>(evaluation_status.value().as_object())) {
+ // Set evaluation status to Await(evaluation status.[[Value]]).
+ HTML::TemporaryExecutionContext execution_context { settings, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ auto promise = WebIDL::create_resolved_promise_for(settings.global_object(), evaluation_status.value());
+
+ auto state = adopt_ref(*new PendingEvaluation);
+ state->on_complete = move(on_complete);
+ state->serialization_options = serialization_options;
+ state->result_ownership = result_ownership;
+
+ state->environment_id = realm_id(settings);
+ state->promise = promise;
+ pending_evaluations().ensure(state->environment_id).append(state);
+
+ WebIDL::react_to_promise(promise,
+ GC::create_function(GC::Heap::the(), [settings = GC::Ref { settings }, state](JS::Value value) -> WebIDL::ExceptionOr<JS::Value> {
+ if (!state->on_complete)
+ return JS::js_undefined();
+ HTML::TemporaryExecutionContext execution_context { *settings, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ state->complete(JsonValue { evaluation_result_success(*settings, value, state->serialization_options, state->result_ownership) });
+ return JS::js_undefined();
+ }),
+ GC::create_function(GC::Heap::the(), [settings = GC::Ref { settings }, state](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
+ if (!state->on_complete)
+ return JS::js_undefined();
+ HTML::TemporaryExecutionContext execution_context { *settings, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ state->complete(JsonValue { evaluation_result_exception(*settings, reason, state->result_ownership) });
+ return JS::js_undefined();
+ }));
+ return;
+ }
+
+ HTML::TemporaryExecutionContext execution_context { settings };
+
+ // If evaluation status.[[Type]] is throw:
+ if (evaluation_status.is_abrupt()) {
+ on_complete(JsonValue { evaluation_result_exception(settings, evaluation_status.value(), result_ownership) });
+ return;
+ }
+
+ // Assert: evaluation status.[[Type]] is normal.
+ on_complete(JsonValue { evaluation_result_success(settings, evaluation_status.value(), serialization_options, result_ownership) });
+}
+
+#define TRY_OR_COMPLETE(expression) \
+ ({ \
+ /* Ignore -Wshadow to allow nesting the macro. */ \
+ AK_IGNORE_DIAGNOSTIC("-Wshadow", \
+ auto&& _temporary_result = (expression)); \
+ static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
+ "Do not return a reference from a fallible expression"); \
+ if (_temporary_result.is_error()) [[unlikely]] { \
+ on_complete(_temporary_result.release_error()); \
+ return; \
+ } \
+ _temporary_result.release_value(); \
+ })
+
+// https://w3c.github.io/webdriver-bidi/#command-script-evaluate
+void evaluate(HTML::Navigable& navigable, JsonObject const& params, OnCommandComplete on_complete)
+{
+ auto source = TRY_OR_COMPLETE(get_string(params, "expression"sv));
+
+ // 1. Let realm be the result of trying to get a realm from a target given the value of the target field of command
+ // parameters.
+ auto& settings = *TRY_OR_COMPLETE(get_a_realm_from_a_target(navigable, params));
+
+ // 2. Let realm id be realm's realm id.
+ // 3. Let environment settings be the environment settings object whose realm execution context's Realm component is
+ // realm.
+ auto& environment_settings = settings;
+
+ // 4. Let source be the value of the expression field of command parameters.
+ // 5. Let await promise be the value of the awaitPromise field of command parameters.
+ auto await_promise = TRY_OR_COMPLETE(get_bool(params, "awaitPromise"sv));
+
+ // 6. Let serialization options be the value of the serializationOptions field of command parameters, if present, or
+ // otherwise a map matching the script.SerializationOptions production with the fields set to their default
+ // values.
+ auto serialization_options = TRY_OR_COMPLETE(get_serialization_options(params));
+
+ // 7. Let result ownership be the value of the resultOwnership field of command parameters, if present, or none
+ // otherwise.
+ auto result_ownership = TRY_OR_COMPLETE(get_result_ownership(params));
+
+ auto user_activation = TRY_OR_COMPLETE(get_optional_bool(params, "userActivation"sv, false));
+
+ // 8. Let options be the default script fetch options.
+ // 9. Let base URL be the API base URL of environment settings.
+ auto base_url = environment_settings.api_base_url();
+
+ // 10. Let bypassDisabledScripting be true.
+ // 11. Let script be the result of create a classic script with source, environment settings, base URL, options and
+ // bypassDisabledScripting.
+ auto script = HTML::ClassicScript::create({}, Utf16String::from_utf8(source), environment_settings, base_url);
+
+ // 12. If command parameters["userActivation"] is true, run activation notification steps.
+ if (user_activation)
+ run_activation_notification_steps(settings);
+
+ // 13. Prepare to run script with environment settings.
+ // 14. Set evaluation status to ScriptEvaluation(script's record).
+ // 16. Clean up after running script with environment settings.
+ // NB: Running the script prepares to run it and cleans up after running it.
+ auto evaluation_status = script->run(HTML::ClassicScript::RethrowErrors::Yes);
+
+ // 15. If evaluation status.[[Type]] is normal, await promise is true, and IsPromise(evaluation status.[[Value]]):
+ // 1. Set evaluation status to Await(evaluation status.[[Value]]).
+ // 17. If evaluation status.[[Type]] is throw:
+ // 1. Let exception details be the result of get exception details with realm, evaluation status, result
+ // ownership and session.
+ // 2. Return a new map matching the script.EvaluationResultException production, with the realm field set to
+ // realm id, and the exceptionDetails field set to exception details.
+ // 18. Assert: evaluation status.[[Type]] is normal.
+ // 19. Let result be the result of serialize as a remote value with evaluation status.[[Value]], serialization
+ // options, result ownership, a new map as serialization internal map, realm and session.
+ // 20. Return a new map matching the script.EvaluationResultSuccess production, with the with the realm field set to
+ // realm id, and the result field set to result.
+ complete_evaluation(settings, move(evaluation_status), await_promise, serialization_options, result_ownership, move(on_complete));
+}
+
+// https://w3c.github.io/webdriver-bidi/#evaluate-function-body
+static JS::Completion evaluate_function_body(StringView function_declaration, HTML::EnvironmentSettingsObject& environment_settings, URL::URL const& base_url)
+{
+ // NB: the function declaration is parenthesized and evaluated.
+
+ // 1. Let bypassDisabledScripting be true.
+ // 2. Let parenthesized function declaration be concatenate «"(", function declaration, ")"»
+ auto parenthesized_function_declaration = Utf16String::formatted("({})", function_declaration);
+
+ // 3. Let function script be the result of create a classic script with parenthesized function declaration,
+ // environment settings, base URL, options and bypassDisabledScripting.
+ auto function_script = HTML::ClassicScript::create({}, parenthesized_function_declaration, environment_settings, base_url);
+
+ // 4. Prepare to run script with environment settings.
+ // 5. Let function body evaluation status be ScriptEvaluation(function script's record).
+ // 6. Clean up after running script with environment settings.
+ // NB: Running the script prepares to run it and cleans up after running it.
+ // 7. Return function body evaluation status.
+ return function_script->run(HTML::ClassicScript::RethrowErrors::Yes);
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-script-callFunction
+void call_function(HTML::Navigable& navigable, JsonObject const& params, OnCommandComplete on_complete)
+{
+ auto function_declaration = TRY_OR_COMPLETE(get_string(params, "functionDeclaration"sv));
+ auto await_promise = TRY_OR_COMPLETE(get_bool(params, "awaitPromise"sv));
+
+ // 1. Let realm be the result of trying to get a realm from a target given the value of the target field of command
+ // parameters.
+ auto& settings = *TRY_OR_COMPLETE(get_a_realm_from_a_target(navigable, params));
+ auto& vm = settings.global_object().vm();
+
+ // 2. Let realm id be realm's realm id.
+ // 3. Let environment settings be the environment settings object whose realm execution context's Realm component is
+ // realm.
+ auto& environment_settings = settings;
+
+ HTML::TemporaryExecutionContext execution_context { settings };
+
+ // 4. Let command arguments be the value of the arguments field of command parameters.
+ // 5. Let deserialized arguments be an empty list.
+ GC::RootVector<JS::Value> deserialized_arguments;
+
+ // 6. If command arguments is not null, set deserialized arguments to the result of trying to deserialize arguments
+ // given realm, command arguments and session.
+ if (auto command_arguments = params.get("arguments"sv); command_arguments.has_value()) {
+ if (!command_arguments->is_array())
+ return on_complete(invalid_argument("Parameter 'arguments' must be a list"sv));
+
+ // https://w3c.github.io/webdriver-bidi/#deserialize-arguments
+ for (auto const& serialized_argument : command_arguments->as_array().values())
+ deserialized_arguments.append(TRY_OR_COMPLETE(deserialize_local_value(serialized_argument, settings)));
+ }
+
+ // 7. Let this parameter be the value of the this field of command parameters.
+ // 8. Let this object be null.
+ JS::Value this_object = JS::js_null();
+
+ // 9. If this parameter is not null, set this object to the result of trying to deserialize local value given this
+ // parameter, realm and session.
+ if (auto this_parameter = params.get("this"sv); this_parameter.has_value())
+ this_object = TRY_OR_COMPLETE(deserialize_local_value(*this_parameter, settings));
+
+ // 10. Let function declaration be the value of the functionDeclaration field of command parameters.
+ // 11. Let await promise be the value of the awaitPromise field of command parameters.
+
+ // 12. Let serialization options be the value of the serializationOptions field of command parameters, if present, or
+ // otherwise a map matching the script.SerializationOptions production with the fields set to their default
+ // values.
+ auto serialization_options = TRY_OR_COMPLETE(get_serialization_options(params));
+
+ // 13. Let result ownership be the value of the resultOwnership field of command parameters, if present, or none
+ // otherwise.
+ auto result_ownership = TRY_OR_COMPLETE(get_result_ownership(params));
+
+ auto user_activation = TRY_OR_COMPLETE(get_optional_bool(params, "userActivation"sv, false));
+
+ // 14. Let base URL be the API base URL of environment settings.
+ auto base_url = environment_settings.api_base_url();
+
+ // 15. Let options be the default script fetch options.
+ // 16. Let function body evaluation status be the result of evaluate function body with function declaration,
+ // environment settings, base URL, and options.
+ auto function_body_evaluation_status = evaluate_function_body(function_declaration, environment_settings, base_url);
+
+ // 17. If function body evaluation status.[[Type]] is throw:
+ if (function_body_evaluation_status.is_abrupt()) {
+ // 1. Let exception details be the result of get exception details given realm, function body evaluation status,
+ // result ownership and session.
+ // 2. Return a new map matching the script.EvaluationResultException production, with the exceptionDetails field
+ // set to exception details.
+ on_complete(JsonValue { evaluation_result_exception(settings, function_body_evaluation_status.value(), result_ownership) });
+ return;
+ }
+
+ // 18. Let function object be function body evaluation status.[[Value]].
+ auto function_object = function_body_evaluation_status.value();
+
+ // 19. If IsCallable(function object) is false:
+ if (!function_object.is_function()) {
+ // 1. Return an error with error code invalid argument
+ return on_complete(invalid_argument("Function declaration is not a function"sv));
+ }
+
+ // 20. If command parameters["userActivation"] is true, run activation notification steps.
+ if (user_activation)
+ run_activation_notification_steps(settings);
+
+ // 21. Prepare to run script with environment settings.
+ HTML::prepare_to_run_script(environment_settings);
+
+ // 22. Set evaluation status to Call(function object, this object, deserialized arguments).
+ auto call_result = JS::call(vm, function_object, this_object, deserialized_arguments.span());
+ JS::Completion evaluation_status = call_result.is_error() ? JS::Completion { call_result.release_error() } : JS::normal_completion(call_result.release_value());
+
+ // 23. If evaluation status.[[Type]] is normal, and await promise is true, and IsPromise(evaluation
+ // status.[[Value]]):
+ // 1. Set evaluation status to Await(evaluation status.[[Value]]).
+ // 24. Clean up after running script with environment settings.
+ HTML::clean_up_after_running_script(environment_settings);
+
+ // 25. If evaluation status.[[Type]] is throw:
+ // 1. Let exception details be the result of get exception details given realm, evaluation status, result
+ // ownership and session.
+ // 2. Return a new map matching the script.EvaluationResultException production, with the exceptionDetails field
+ // set to exception details.
+ // 26. Assert: evaluation status.[[Type]] is normal.
+ // 27. Let result be the result of serialize as a remote value with evaluation status.[[Value]], serialization
+ // options, result ownership, a new map as serialization internal map, realm and session.
+ // 28. Return a new map matching the script.EvaluationResultSuccess production, with the realm field set to realm id,
+ // and the result field set to result.
+ complete_evaluation(settings, move(evaluation_status), await_promise, serialization_options, result_ownership, move(on_complete));
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-script-disown
+Response disown(HTML::Navigable& navigable, JsonObject const& params)
+{
+ auto handles = params.get("handles"sv);
+ if (!handles.has_value() || !handles->is_array())
+ return invalid_argument("Parameter 'handles' must be a list of strings"sv);
+ for (auto const& handle : handles->as_array().values()) {
+ if (!handle.is_string())
+ return invalid_argument("Parameter 'handles' must be a list of strings"sv);
+ }
+
+ // 1. Let realm be the result of trying to get a realm from a target given the value of the target field of command
+ // parameters.
+ auto& settings = *TRY(get_a_realm_from_a_target(navigable, params));
+
+ // 2. Let handles the value of the handles field of command parameters.
+ // 3. For each handle id of handles:
+ for (auto const& handle_id : handles->as_array().values()) {
+ // 1. Let handle map be realm's handle object map
+ // 2. If handle map contains handle id, remove handle id from the handle map.
+ remove_handle(settings, handle_id.as_string());
+ }
+
+ // 4. Return success with data null.
+ return JsonValue {};
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-script-getRealms
+Response get_realms(HTML::Navigable& navigable, JsonObject const& params)
+{
+ auto type = params.get_string("type"sv);
+
+ // 1. Let environment settings be a list of all the environment settings objects that have their execution ready flag
+ // set.
+ // 2. If command parameters contains context:
+ // 1. Let navigable be the result of trying to get a navigable with command parameters["context"].
+ // 2. Let document be navigable's active document.
+ // 3. Let navigable environment settings be a list.
+ // 4. For each settings of environment settings:
+ // 1. If any of the following conditions hold:
+ // - The associated Document of settings' relevant global object is document
+ // - The global object specified by settings is a WorkerGlobalScope with document in its owner set
+ // Append settings to navigable environment settings.
+ // 5. Set environment settings to navigable environment settings.
+ // NB: The browser process asks the process hosting each navigable's active document for the realms of that
+ // document.
+ // FIXME: Include the realms of workers.
+ GC::ConservativeVector<HTML::EnvironmentSettingsObject*> environment_settings;
+ if (auto* local_navigable = as_if<HTML::LocalNavigable>(navigable)) {
+ if (auto document = local_navigable->active_document()) {
+ auto& settings = document->relevant_settings_object();
+ if (settings.execution_ready)
+ environment_settings.append(&settings);
+ }
+ }
+
+ // 3. Let realms be a list.
+ JsonArray realms;
+
+ // 4. For each settings of environment settings:
+ for (auto* settings : environment_settings) {
+ // 1. Let realm info be the result of get the realm info given settings.
+ auto realm_info = get_the_realm_info(*settings);
+
+ // 2. If command parameters contains type and realm info["type"] is not equal to command parameters["type"] then
+ // continue.
+ if (type.has_value() && realm_info.has_value() && realm_info->get_string("type"sv) != *type)
+ continue;
+
+ // 3. If realm info is not null, append realm info to realms.
+ if (realm_info.has_value())
+ realms.must_append(realm_info.release_value());
+ }
+
+ // 5. Let body be a map matching the script.GetRealmsResult production, with the realms field set to realms.
+ JsonObject body;
+ body.set("realms"sv, move(realms));
+
+ // 6. Return success with data body.
+ return JsonValue { move(body) };
+}
+
+// https://w3c.github.io/webdriver-bidi/#run-webdriver-bidi-preload-scripts
+void run_webdriver_bidi_preload_scripts(HTML::EnvironmentSettingsObject& environment_settings)
+{
+ // NB: The preload scripts may spin the event loop, which may replace the session state, so they are copied.
+ auto preload_scripts = session_state().preload_scripts;
+ if (preload_scripts.is_empty())
+ return;
+
+ // 1. Let document be environment settings' relevant global object's associated Document.
+ auto* window = HTML::window_from_global_object(environment_settings.global_object());
+ if (!window)
+ return;
+ auto& document = window->associated_document();
+
+ // 2. Let navigable be document's navigable.
+ auto navigable = document.navigable();
+ if (!navigable)
+ return;
+
+ // 3. Let user context be navigable's associated user context.
+ // 4. Let user context id be user context's user context id.
+ auto user_context_id = DEFAULT_USER_CONTEXT_ID;
+
+ // 5. For each session in active BiDi sessions:
+ // 1. For each preload script in session's preload script map's values:
+ for (auto const& preload_script : preload_scripts) {
+ // 1. If preload script's user contexts's size is not zero:
+ // 1. If preload script's user contexts does not contain user context id, continue.
+ if (!preload_script.user_contexts.is_empty() && !preload_script.user_contexts.contains_slow(user_context_id))
+ continue;
+
+ // 2. If preload script's contexts is not null:
+ if (preload_script.contexts.has_value()) {
+ // 1. Let navigable id be navigable’s top-level traversable's id.
+ auto top_level_traversable_id = navigable_id(*navigable->top_level_traversable());
+
+ // 2. If preload script's contexts does not contain navigable id, continue.
+ if (!preload_script.contexts->contains_slow(top_level_traversable_id))
+ continue;
+ }
+
+ // 3. If preload script's sandbox is not null, let realm be get or create a sandbox realm with preload script's
+ // sandbox and navigable. Otherwise let realm be environment settings' realm execution context's Realm
+ // component.
+ // FIXME: Implement sandbox realms.
+ if (preload_script.sandbox.has_value())
+ continue;
+
+ // 4. Let exception reporting global be be environment settings' realm execution context's Realm component's
+ // global object.
+ auto& exception_reporting_global = environment_settings.global_object();
+
+ HTML::TemporaryExecutionContext execution_context { environment_settings };
+
+ // 5. Let arguments be preload script's arguments.
+ // 6. Let deserialized arguments be an empty list.
+ GC::RootVector<JS::Value> deserialized_arguments;
+
+ // 7. For each argument in arguments:
+ if (preload_script.arguments.is_array()) {
+ for (auto const& argument : preload_script.arguments.as_array().values()) {
+ // 1. Let channel be create a channel with session, realm and argument.
+ // 2. Append channel to deserialized arguments.
+ if (argument.is_object())
+ deserialized_arguments.append(create_a_channel(environment_settings, argument.as_object()));
+ }
+ }
+
+ // 8. Let base URL be the API base URL of environment settings.
+ auto base_url = environment_settings.api_base_url();
+
+ // 9. Let options be the default script fetch options.
+ // 10. Let function declaration be preload script's function declaration.
+ // 11. Let function body evaluation status be the result of evaluate function body with function declaration,
+ // environment settings, base URL, and options.
+ auto function_body_evaluation_status = evaluate_function_body(preload_script.function_declaration, environment_settings, base_url);
+
+ // 12. If function body evaluation status is an abrupt completion, then report an exception given by function
+ // body evaluation status.[[Value]] for exception reporting global.
+ if (function_body_evaluation_status.is_abrupt()) {
+ HTML::report_an_exception(exception_reporting_global, function_body_evaluation_status.value());
+ continue;
+ }
+
+ // 13. Let function object be function body evaluation status.[[Value]].
+ auto function_object = function_body_evaluation_status.value();
+
+ // 14. If IsCallable(function object) is false:
+ if (!function_object.is_function()) {
+ // 1. Let error be a new TypeError object in realm.
+ auto error = BindingsGlue::create_preload_type_error(environment_settings);
+
+ // 2. Report an exception error for exception reporting global.
+ HTML::report_an_exception(exception_reporting_global, error);
+ continue;
+ }
+
+ // 15. Prepare to run script with environment settings.
+ HTML::prepare_to_run_script(environment_settings);
+
+ // 16. Set evaluation status to Call(function object, null, deserialized arguments).
+ auto evaluation_status = JS::call(environment_settings.global_object().vm(), function_object, JS::js_null(), deserialized_arguments.span());
+
+ // 17. Clean up after running script with environment settings.
+ HTML::clean_up_after_running_script(environment_settings);
+
+ // 18. If evaluation status is an abrupt completion, then report an exception given by evaluation
+ // status.[[Value]] for exception reporting global.
+ if (evaluation_status.is_error())
+ HTML::report_an_exception(exception_reporting_global, evaluation_status.error_value());
+ }
+}
+
+}
diff --git a/Libraries/LibWeb/WebDriver/BiDi/Script.h b/Libraries/LibWeb/WebDriver/BiDi/Script.h
new file mode 100644
index 00000000000..675e6d05c84
--- /dev/null
+++ b/Libraries/LibWeb/WebDriver/BiDi/Script.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Function.h>
+#include <AK/JsonObject.h>
+#include <AK/JsonValue.h>
+#include <AK/Optional.h>
+#include <LibJS/Forward.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
+#include <LibWebCommon/WebDriver/Response.h>
+
+// https://w3c.github.io/webdriver-bidi/#module-script
+namespace Web::WebDriver::BiDi {
+
+using OnCommandComplete = Function<void(Response)>;
+
+// https://w3c.github.io/webdriver-bidi/#command-script-evaluate
+WEB_API void evaluate(HTML::Navigable&, JsonObject const& params, OnCommandComplete);
+
+// https://w3c.github.io/webdriver-bidi/#command-script-callFunction
+WEB_API void call_function(HTML::Navigable&, JsonObject const& params, OnCommandComplete);
+
+// https://w3c.github.io/webdriver-bidi/#command-script-disown
+WEB_API Response disown(HTML::Navigable&, JsonObject const& params);
+
+// https://w3c.github.io/webdriver-bidi/#command-script-getRealms
+// NB: The realms of the given navigable's active document, which the browser process gathers for each navigable.
+WEB_API Response get_realms(HTML::Navigable&, JsonObject const& params);
+
+// https://w3c.github.io/webdriver-bidi/#get-the-realm-info
+Optional<JsonObject> get_the_realm_info(HTML::EnvironmentSettingsObject&);
+
+// https://w3c.github.io/webdriver-bidi/#get-the-source
+JsonObject get_the_source(HTML::EnvironmentSettingsObject&);
+
+// https://w3c.github.io/webdriver-bidi/#create-a-channel
+JS::Value create_a_channel(HTML::EnvironmentSettingsObject&, JsonObject const& protocol_value);
+
+// NB: The evaluations that await a promise of the realm, which is destroyed, complete with an error.
+void fail_pending_evaluations(HTML::EnvironmentSettingsObject&);
+void fail_all_pending_evaluations();
+
+// https://w3c.github.io/webdriver-bidi/#run-webdriver-bidi-preload-scripts
+void run_webdriver_bidi_preload_scripts(HTML::EnvironmentSettingsObject&);
+
+}
diff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txt
index 8c9b29fee7d..29fd96811a8 100644
--- a/Libraries/LibWebCommon/CMakeLists.txt
+++ b/Libraries/LibWebCommon/CMakeLists.txt
@@ -62,6 +62,7 @@ set(SOURCES
StorageAPI/StorageEndpoint.cpp
StorageAPI/StorageKey.cpp
UpgradeInsecureRequests/InsecureRequestsPolicy.cpp
+ WebDriver/BiDi.cpp
WebDriver/Capabilities.cpp
WebDriver/Client.cpp
WebDriver/Error.cpp
@@ -110,6 +111,7 @@ compile_ipc(Page/TextEditingCommand.ipc Page/TextEditingCommandCodecs.h)
compile_ipc(PixelUnits.ipc PixelUnitsCodecs.h)
compile_ipc(WebView/AccessibilityNodeData.ipc WebView/AccessibilityNodeDataCodecs.h)
compile_ipc(WebView/DictionaryLookup.ipc WebView/DictionaryLookupCodecs.h)
+compile_ipc(WebDriver/BiDi.ipc WebDriver/BiDiCodecs.h)
# NB: The protocols between the UI process and the processes it hosts web content in only use LibWebCommon types, so
# both sides generate their endpoints from here.
diff --git a/Libraries/LibWebCommon/WebDriver/BiDi.cpp b/Libraries/LibWebCommon/WebDriver/BiDi.cpp
new file mode 100644
index 00000000000..dbd042c8643
--- /dev/null
+++ b/Libraries/LibWebCommon/WebDriver/BiDi.cpp
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/JsonObject.h>
+#include <LibWebCommon/WebDriver/BiDi.h>
+
+namespace Web::WebDriver {
+
+// js-uint = 0..9007199254740991
+Optional<u64> as_js_uint(JsonValue const& value)
+{
+ static constexpr u64 MAXIMUM_SAFE_INTEGER = 9007199254740991;
+
+ if (!value.is_number())
+ return {};
+
+ return value.as_number().visit(
+ [](u64 number) -> Optional<u64> {
+ if (number > MAXIMUM_SAFE_INTEGER)
+ return {};
+ return number;
+ },
+ [](i64 number) -> Optional<u64> {
+ if (number < 0 || static_cast<u64>(number) > MAXIMUM_SAFE_INTEGER)
+ return {};
+ return static_cast<u64>(number);
+ },
+ [](double number) -> Optional<u64> {
+ if (!(number >= 0) || number > static_cast<double>(MAXIMUM_SAFE_INTEGER))
+ return {};
+ auto integer = static_cast<u64>(number);
+ if (static_cast<double>(integer) != number)
+ return {};
+ return integer;
+ });
+}
+
+// https://w3c.github.io/webdriver-bidi/#type-script-SerializationOptions
+ErrorOr<SerializationOptions, Error> parse_serialization_options(JsonValue const& value)
+{
+ // script.SerializationOptions = {
+ // ? maxDomDepth: (js-uint / null) .default 0,
+ // ? maxObjectDepth: (js-uint / null) .default null,
+ // ? includeShadowTree: ("none" / "open" / "all") .default "none",
+ // }
+ if (!value.is_object())
+ return Error::from_code(ErrorCode::InvalidArgument, "Serialization options must be an object"sv);
+
+ auto const& object = value.as_object();
+ SerializationOptions options;
+
+ if (auto max_dom_depth = object.get("maxDomDepth"sv); max_dom_depth.has_value()) {
+ if (max_dom_depth->is_null()) {
+ options.max_dom_depth = {};
+ } else {
+ options.max_dom_depth = as_js_uint(*max_dom_depth);
+ if (!options.max_dom_depth.has_value())
+ return Error::from_code(ErrorCode::InvalidArgument, "maxDomDepth must be an unsigned integer or null"sv);
+ }
+ }
+
+ if (auto max_object_depth = object.get("maxObjectDepth"sv); max_object_depth.has_value()) {
+ if (!max_object_depth->is_null()) {
+ options.max_object_depth = as_js_uint(*max_object_depth);
+ if (!options.max_object_depth.has_value())
+ return Error::from_code(ErrorCode::InvalidArgument, "maxObjectDepth must be an unsigned integer or null"sv);
+ }
+ }
+
+ if (auto include_shadow_tree = object.get("includeShadowTree"sv); include_shadow_tree.has_value()) {
+ auto string = include_shadow_tree->is_string() ? include_shadow_tree->as_string() : String {};
+ if (string == "none"sv)
+ options.include_shadow_tree = SerializationOptions::IncludeShadowTree::None;
+ else if (string == "open"sv)
+ options.include_shadow_tree = SerializationOptions::IncludeShadowTree::Open;
+ else if (string == "all"sv)
+ options.include_shadow_tree = SerializationOptions::IncludeShadowTree::All;
+ else
+ return Error::from_code(ErrorCode::InvalidArgument, "includeShadowTree must be \"none\", \"open\" or \"all\""sv);
+ }
+
+ return options;
+}
+
+}
diff --git a/Libraries/LibWebCommon/WebDriver/BiDi.h b/Libraries/LibWebCommon/WebDriver/BiDi.h
new file mode 100644
index 00000000000..b272241c490
--- /dev/null
+++ b/Libraries/LibWebCommon/WebDriver/BiDi.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/JsonValue.h>
+#include <AK/Optional.h>
+#include <AK/String.h>
+#include <AK/Vector.h>
+#include <AK/kmalloc.h>
+#include <LibWebCommon/Export.h>
+#include <LibWebCommon/WebDriver/Error.h>
+
+namespace Web::WebDriver {
+
+// js-uint = 0..9007199254740991
+// https://w3c.github.io/webdriver-bidi/#protocol-definition
+WEBCOMMON_API Optional<u64> as_js_uint(JsonValue const&);
+
+// https://w3c.github.io/webdriver-bidi/#type-script-SerializationOptions
+struct WEBCOMMON_API SerializationOptions {
+ enum class IncludeShadowTree : u8 {
+ None,
+ Open,
+ All,
+ };
+
+ // NB: An empty depth is null, which does not limit the depth.
+ Optional<u64> max_dom_depth { 0 };
+ Optional<u64> max_object_depth {};
+ IncludeShadowTree include_shadow_tree { IncludeShadowTree::None };
+};
+
+WEBCOMMON_API ErrorOr<SerializationOptions, Error> parse_serialization_options(JsonValue const&);
+
+// https://w3c.github.io/webdriver-bidi/#preload-script
+struct WEBCOMMON_API BiDiPreloadScript {
+ String id;
+ String function_declaration;
+ JsonValue arguments;
+ Optional<Vector<String>> contexts;
+ Optional<String> sandbox;
+ Vector<String> user_contexts;
+};
+
+// The state of the BiDi session that processes hosting web content need: which events some subscription enables, and
+// the preload scripts to run in new windows.
+struct WEBCOMMON_API BiDiSessionState {
+ AK_ALLOC_WITH_KMALLOC;
+
+ bool is_active { false };
+ Vector<String> enabled_events;
+ Vector<BiDiPreloadScript> preload_scripts;
+};
+
+}
+
+#include <LibWebCommon/WebDriver/BiDiCodecs.h>
diff --git a/Libraries/LibWebCommon/WebDriver/BiDi.ipc b/Libraries/LibWebCommon/WebDriver/BiDi.ipc
new file mode 100644
index 00000000000..f6a47711c5f
--- /dev/null
+++ b/Libraries/LibWebCommon/WebDriver/BiDi.ipc
@@ -0,0 +1,23 @@
+// Copyright (c) 2026-present, the Ladybird developers.
+
+// NB: The IPC compiler cannot check that each struct here lists every field of its C++ type. A field left out
+// here does not cross IPC.
+
+#include <LibWebCommon/WebDriver/BiDi.h>
+
+[ExistingCpp]
+struct Web::WebDriver::BiDiPreloadScript {
+ String id;
+ String function_declaration;
+ JsonValue arguments;
+ Optional<Vector<String>> contexts;
+ Optional<String> sandbox;
+ Vector<String> user_contexts;
+}
+
+[ExistingCpp]
+struct Web::WebDriver::BiDiSessionState {
+ bool is_active;
+ Vector<String> enabled_events;
+ Vector<Web::WebDriver::BiDiPreloadScript> preload_scripts;
+}
diff --git a/Libraries/LibWebCommon/WebDriver/Capabilities.cpp b/Libraries/LibWebCommon/WebDriver/Capabilities.cpp
index d15a31aebdb..d9fbebcb40e 100644
--- a/Libraries/LibWebCommon/WebDriver/Capabilities.cpp
+++ b/Libraries/LibWebCommon/WebDriver/Capabilities.cpp
@@ -328,12 +328,11 @@ static JsonValue match_capabilities(JsonObject const& capabilities, SessionFlags
// https://w3c.github.io/webdriver-bidi/#type-session-CapabilityRequest
if (name == "webSocketUrl"sv) {
// 1. If value is false, return success with data null.
+ // NB: This is the match value, which is then not set on matched capabilities.
if (!value.as_bool())
- return AK::Error::from_string_literal("webSocketUrl");
+ return {};
// 2. Return success with data value.
- // FIXME: Remove this when we support BIDI communication.
- return AK::Error::from_string_literal("webSocketUrl");
}
}
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index 9fd12288beb..bef5bb87249 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -73,6 +73,7 @@
#include <LibWebView/UserAgent.h>
#include <LibWebView/Utilities.h>
#include <LibWebView/WebContentClient.h>
+#include <LibWebView/WebDriverBiDi.h>
#include <LibWebView/WebDriverBrowserConnection.h>
#include <LibWebView/WebWorkerClient.h>
#include <LibWebView/WorkerProcessManager.h>
@@ -1159,6 +1160,10 @@ ErrorOr<NonnullRefPtr<WebContentClient>> Application::create_web_content_client(
client->async_set_site_compatibility_data(m_site_compatibility_data);
connect_to_image_decoder(*client, move(image_decoder));
+ // NB: A WebDriver BiDi session gives its state to every process hosting web content when it changes.
+ if (auto* webdriver_bidi = WebDriverBiDi::the(); webdriver_bidi && webdriver_bidi->session_state().is_active)
+ client->async_set_webdriver_bidi_session_state(webdriver_bidi->session_state());
+
if (m_content_blocker_list_buffer.has_value())
client->async_set_content_blockers(*m_content_blocker_list_buffer);
@@ -1340,6 +1345,9 @@ Optional<u64> Application::webdriver_page_load_timeout() const
void Application::complete_webdriver_content_command(u64 command_id, Web::WebDriver::Response response)
{
+ if (auto* webdriver_bidi = WebDriverBiDi::the(); webdriver_bidi && webdriver_bidi->did_complete_content_command(command_id, response))
+ return;
+
if (m_webdriver_browser_connection)
m_webdriver_browser_connection->async_command_complete(command_id, move(response));
}
diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txt
index a7d8fe10e6e..5ba0c7ca79e 100644
--- a/Libraries/LibWebView/CMakeLists.txt
+++ b/Libraries/LibWebView/CMakeLists.txt
@@ -76,6 +76,7 @@ set(SOURCES
WebContentClient.cpp
WebContentPage.cpp
WebContentTestClient.cpp
+ WebDriverBiDi.cpp
WebDriverBrowserConnection.cpp
WebUI.cpp
WebUI/BookmarksUI.cpp
diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cpp
index 2729b1ed4ec..5879748dbea 100644
--- a/Libraries/LibWebView/CanonicalNavigable.cpp
+++ b/Libraries/LibWebView/CanonicalNavigable.cpp
@@ -26,6 +26,7 @@
#include <LibWebView/PictureInPictureManager.h>
#include <LibWebView/ViewImplementation.h>
#include <LibWebView/WebContentClient.h>
+#include <LibWebView/WebDriverBiDi.h>
namespace WebView {
@@ -192,8 +193,11 @@ void CanonicalNavigable::begin_navigation(Web::HTML::PreparedNavigationDescripto
// 9. If navigable's active document's unload counter is greater than 0, then invoke WebDriver BiDi navigation failed
// with navigable and a WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url
// is url, and return.
- if (active_document().unload_counter() > 0)
+ if (active_document().unload_counter() > 0) {
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->navigation_failed(*this, { .id = navigation_id, .status = WebDriverBiDi::NavigationStatusType::Canceled, .url = url });
return;
+ }
// NB: The page hosting navigable's active document, which has its container if any process does, runs steps 10,
// 11, and 15.
@@ -243,14 +247,18 @@ void CanonicalNavigable::begin_navigation(Web::HTML::PreparedNavigationDescripto
// 16. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
auto target_snapshot_params = snapshot_target_snapshot_params();
- // FIXME: 17. Invoke WebDriver BiDi navigation started with navigable and a new WebDriver BiDi navigation status whose
- // id is navigationId, status is "pending", and url is url.
+ // 17. Invoke WebDriver BiDi navigation started with navigable and a new WebDriver BiDi navigation status whose id is
+ // navigationId, status is "pending", and url is url.
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->navigation_started(*this, { .id = navigation_id, .status = WebDriverBiDi::NavigationStatusType::Pending, .url = url });
// 18. If navigable's ongoing navigation is "traversal", then:
// AD-HOC: A navigation from the browser's UI goes on, and takes the navigable over from the traversal.
if (m_ongoing_navigation.has<Traversal>() && user_involvement != Web::HTML::UserNavigationInvolvement::BrowserUI) {
- // FIXME: 1. Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status
- // whose id is navigationId, status is "canceled", and url is url.
+ // 1. Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status whose id
+ // is navigationId, status is "canceled", and url is url.
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->navigation_failed(*this, { .id = navigation_id, .status = WebDriverBiDi::NavigationStatusType::Canceled, .url = url });
// 2. Return.
return;
@@ -259,8 +267,11 @@ void CanonicalNavigable::begin_navigation(Web::HTML::PreparedNavigationDescripto
// NB: The process hosting navigable's active document evaluates a javascript: URL at step 20. A lost document is
// not there to evaluate it against, and the navigation does nothing.
auto is_javascript_url = url.scheme() == "javascript"sv;
- if (is_javascript_url && !host)
+ if (is_javascript_url && !host) {
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->navigation_failed(*this, { .id = navigation_id, .status = WebDriverBiDi::NavigationStatusType::Canceled, .url = url });
return;
+ }
// 19. Set the ongoing navigation for navigable to navigationId.
// NB: It is set with the navigation's steps: evaluating a javascript: URL from step 20, or those step 23 runs.
@@ -293,6 +304,8 @@ void CanonicalNavigable::begin_navigation(Web::HTML::PreparedNavigationDescripto
auto worker = traversable.page_hosting(*this);
if (!worker || !worker->is_open()) {
clear_ongoing_navigation();
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->navigation_failed(*this, { .id = navigation_id, .status = WebDriverBiDi::NavigationStatusType::Canceled, .url = url });
return;
}
auto start_request = Web::HTML::NavigationStartRequest {
@@ -1470,6 +1483,10 @@ void CanonicalNavigable::set_ongoing_navigation(CanonicalNavigation::Start navig
ongoing_navigation->blob_url = move(blob_url);
m_navigations.append(move(ongoing_navigation));
set_the_ongoing_navigation(move(navigation_id));
+
+ // NB: An admitted navigation supersedes a pending BiDi reload. Late events from an older navigation do not.
+ if (auto* bidi = WebDriverBiDi::the())
+ bidi->navigation_superseded_reload(*this);
}
// Navigate, step 20, in the page hosting navigable's active document.
diff --git a/Libraries/LibWebView/CanonicalTraversable.cpp b/Libraries/LibWebView/CanonicalTraversable.cpp
index 542a4d83b4f..995c08ae837 100644
--- a/Libraries/LibWebView/CanonicalTraversable.cpp
+++ b/Libraries/LibWebView/CanonicalTraversable.cpp
@@ -7,6 +7,7 @@
#include <AK/NeverDestroyed.h>
#include <AK/NumericLimits.h>
#include <AK/StringBuilder.h>
+#include <AK/TemporaryChange.h>
#include <LibCore/EventLoop.h>
#include <LibWebCommon/WebView/SiteIsolation.h>
#include <LibWebView/Application.h>
@@ -19,6 +20,7 @@
#include <LibWebView/StorageJar.h>
#include <LibWebView/ViewImplementation.h>
#include <LibWebView/WebContentClient.h>
+#include <LibWebView/WebDriverBiDi.h>
namespace WebView {
@@ -152,6 +154,13 @@ CanonicalNavigable& CanonicalTraversable::insert(NonnullRefPtr<WebContentPage> r
for_each_page_representing(navigable_ref, [&](WebContentPage& page) {
page.async_insert_remote_navigable({ .id = navigable_ref.id(), .parent_id = parent.id(), .replicated_state = *navigable_ref.replicated_state() });
});
+
+ // https://html.spec.whatwg.org/multipage/document-sequences.html#create-a-new-child-navigable
+ // 13. Invoke WebDriver BiDi navigable created with traversable.
+ // NB: This means the navigable that was created.
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->navigable_created(navigable_ref);
+
return navigable_ref;
}
@@ -499,8 +508,26 @@ Optional<CanonicalNavigable const&> CanonicalTraversable::find(Web::HTML::CrossP
void CanonicalTraversable::remove(CanonicalNavigable& navigable)
{
VERIFY(&navigable != this);
- while (!navigable.children().is_empty())
- remove(*navigable.children().last());
+
+ // https://html.spec.whatwg.org/multipage/document-sequences.html#destroy-a-child-navigable
+ // 10. Invoke WebDriver BiDi navigable destroyed with navigable.
+ // NB: Only the navigable whose container went away is destroyed, while the documents of its descendants are. It is
+ // reported before its descendants are removed, as it was. The navigables of a closing traversable go away with
+ // it, which reports its own destruction.
+ if (auto* webdriver_bidi = WebDriverBiDi::the(); webdriver_bidi && !m_removing_navigable_descendants) {
+ auto const& traversable_state = hosted_state();
+ if (!traversable_state.has_value() || !traversable_state->is_closing)
+ webdriver_bidi->navigable_destroyed(navigable);
+ else
+ webdriver_bidi->top_level_traversable_is_closing(*this);
+ }
+
+ {
+ TemporaryChange removing_descendants { m_removing_navigable_descendants, true };
+ while (!navigable.children().is_empty())
+ remove(*navigable.children().last());
+ }
+
end_history_jobs(navigable);
navigable.clear_ongoing_navigation();
navigable.discard_pending_host();
@@ -662,7 +689,7 @@ ByteString CanonicalTraversable::queued_same_document_session_history_entries_fo
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#reload
// NB: This is a reload from the browser's UI. One by script fires the navigate event in the process hosting the active
// document, which then asks for the reload history step.
-void CanonicalTraversable::reload(BypassCache bypass_cache)
+void CanonicalTraversable::reload(BypassCache bypass_cache, Optional<Utf16String> navigation_id)
{
auto user_involvement = Web::HTML::UserNavigationInvolvement::BrowserUI;
@@ -684,7 +711,10 @@ void CanonicalTraversable::reload(BypassCache bypass_cache)
.navigable_id = id(),
.user_involvement = user_involvement,
};
- enqueue_history_operation(Application::the().allocate_ui_process_cross_process_id(), parameters, {});
+ auto operation_id = Application::the().allocate_ui_process_cross_process_id();
+ if (navigation_id.has_value())
+ m_reload_navigation_ids.set(operation_id, { navigation_id.release_value() });
+ enqueue_history_operation(operation_id, parameters, {});
}
// https://html.spec.whatwg.org/multipage/document-lifecycle.html#nav-stop
@@ -783,7 +813,10 @@ CanonicalTraversable& CanonicalTraversable::create_a_new_top_level_traversable(W
auto& traversable_ref = *traversable;
user_agent_top_level_traversable_set().append(move(traversable));
- // FIXME: 12. Invoke WebDriver BiDi navigable created with traversable and openerNavigableForWebDriver.
+ // 12. Invoke WebDriver BiDi navigable created with traversable and openerNavigableForWebDriver.
+ // NB: openerNavigableForWebDriver is the opener of a traversable that has one.
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->navigable_created(traversable_ref, opener);
// 13. Return traversable.
return traversable_ref;
@@ -1417,6 +1450,8 @@ bool CanonicalTraversable::run_changing_navigable_history_step_job(ApplyHistoryS
}
Optional<Utf16String> finalized_navigation_id;
+ if (auto const* reload = operation.parameters.get_pointer<Web::ReloadHistoryOperationParameters>(); reload && reload->navigable_id == navigable_id)
+ finalized_navigation_id = reload_navigation_id(operation.operation_id);
if (auto const* parameters = operation.parameters.get_pointer<Web::FinalizeCrossDocumentNavigationHistoryOperationParameters>(); parameters && parameters->navigable_id == navigable_id) {
finalized_navigation_id = parameters->navigation_id;
if (auto const& populated_document = changing_navigable.target_entry->document_state->populated_document; populated_document.has_value())
@@ -1559,6 +1594,10 @@ void CanonicalTraversable::did_activate_history_entry(HistoryOperation& operatio
Optional<Utf16String const&> navigation_id;
if (auto navigation = finalized_navigation(operation))
navigation_id = navigation->navigation_id;
+ else if (auto reload = m_reload_navigation_ids.find(operation.operation_id); reload != m_reload_navigation_ids.end() && navigable.is_top_level_traversable()) {
+ navigation_id = reload->value.id;
+ reload->value.activated = true;
+ }
auto const* replaced_document = &navigable.active_document();
// NB: The page that activated the document hosts it: the job's, which hosts the document the job populated, or else
// the navigable's.
@@ -2103,6 +2142,11 @@ void CanonicalTraversable::apply_the_reload_history_step(HistoryOperation& opera
// 1. Let step be traversable's current session history step.
auto step = m_session_history.current_step();
+ if (auto navigation_id = reload_navigation_id(operation.operation_id); navigation_id.has_value()) {
+ if (auto* bidi = WebDriverBiDi::the())
+ bidi->navigation_started(*this, { .id = navigation_id, .status = WebDriverBiDi::NavigationStatusType::Pending, .url = active_document_url() });
+ }
+
// 2. Return the result of applying the history step step to traversable given true, null, null, userInvolvement, and "reload".
apply_history_step(operation, step, true, {}, user_involvement, Web::Bindings::NavigationType::Reload);
}
@@ -2517,7 +2561,15 @@ void CanonicalTraversable::finalize_a_cross_document_navigation(HistoryOperation
apply_the_push_or_replace_history_step(operation, *target_step, parameters.history_handling, parameters.user_involvement);
}
-void CanonicalTraversable::did_not_apply_reload(Web::HTML::CrossProcessId navigable_id)
+Optional<Utf16String> CanonicalTraversable::reload_navigation_id(Web::HTML::CrossProcessId operation_id) const
+{
+ auto it = m_reload_navigation_ids.find(operation_id);
+ if (it == m_reload_navigation_ids.end())
+ return {};
+ return it->value.id;
+}
+
+void CanonicalTraversable::did_not_apply_reload(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id)
{
// AD-HOC: The spec leaves reload pending set when the reload does not apply, so a later history step would reload
// the document anyway.
@@ -2530,6 +2582,8 @@ void CanonicalTraversable::did_not_apply_reload(Web::HTML::CrossProcessId naviga
if (navigable_id != id())
return;
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->reload_did_not_apply(*this, navigation_id);
if (auto view = this->view(); view.has_value())
view->did_not_apply_reload();
}
@@ -2564,7 +2618,13 @@ void CanonicalTraversable::finish_history_operation(Web::HTML::CrossProcessId op
if (operation->requesting_page)
operation->requesting_page->async_history_step_applied(operation_id, *result);
if (auto const* reload = operation->parameters.get_pointer<Web::ReloadHistoryOperationParameters>(); reload && result != Web::HTML::HistoryStepResult::Applied)
- did_not_apply_reload(reload->navigable_id);
+ did_not_apply_reload(reload->navigable_id, reload_navigation_id(operation_id));
+ }
+
+ // NB: A skipped or stale reload job can finish with "applied" without activating a document.
+ if (auto reload = m_reload_navigation_ids.take(operation_id); reload.has_value() && !reload->activated) {
+ if (auto* bidi = WebDriverBiDi::the())
+ bidi->reload_did_not_apply(*this, reload->id);
}
auto committed_step = operation->algorithm ? operation->algorithm->committed_step() : Optional<i32> {};
diff --git a/Libraries/LibWebView/CanonicalTraversable.h b/Libraries/LibWebView/CanonicalTraversable.h
index 37f17911253..65dda1f9ea3 100644
--- a/Libraries/LibWebView/CanonicalTraversable.h
+++ b/Libraries/LibWebView/CanonicalTraversable.h
@@ -163,7 +163,7 @@ public:
Vector<NonnullRefPtr<CanonicalSessionHistoryEntry>> queued_same_document_session_history_entries(CanonicalNavigable const&) const;
ByteString queued_same_document_session_history_entries_for_debug() const;
- void reload(BypassCache);
+ void reload(BypassCache, Optional<Utf16String> navigation_id = {});
void stop_loading();
static CanonicalTraversable& create_a_new_top_level_traversable(Web::HTML::CrossProcessId id, Optional<CanonicalNavigable&> opener, Web::HTML::SessionHistoryEntryDescriptor initial_history_entry, Web::HTML::CrossProcessId document_id);
static bool is_origin_held_by_a_document(URL::Origin const&);
@@ -228,7 +228,8 @@ private:
void resume_applying_the_traverse_history_step(HistoryOperation&, i32 step, Web::HTML::UserNavigationInvolvement);
void update_for_navigable_creation_or_destruction(HistoryOperation&);
void finish_history_operation(Web::HTML::CrossProcessId operation_id, Optional<Web::HTML::HistoryStepResult> = {});
- void did_not_apply_reload(Web::HTML::CrossProcessId navigable_id);
+ void did_not_apply_reload(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id);
+ Optional<Utf16String> reload_navigation_id(Web::HTML::CrossProcessId operation_id) const;
HistoryOperation* ongoing_browser_history_traversal();
void run_browser_ui_traversal_at_queue_position(Function<Optional<i32>()> select_target_step, CheckForCancelation, Function<void()> on_ready, NonnullRefPtr<Core::Promise<Empty>>);
@@ -250,6 +251,12 @@ private:
TraversableApplyHistoryStepState m_apply_history_step_traversable_state;
u64 m_next_sequence_number { 1 };
HashMap<Web::HTML::CrossProcessId, NonnullOwnPtr<HistoryOperation>> m_history_operations;
+ // NB: Navigation IDs for BiDi reloads belong to their queued history operations.
+ struct ReloadNavigation {
+ Utf16String id;
+ bool activated { false };
+ };
+ HashMap<Web::HTML::CrossProcessId, ReloadNavigation> m_reload_navigation_ids;
// The traversal from the browser's UI among the operations, if any.
HistoryOperation* m_browser_history_traversal { nullptr };
RefPtr<WebContentPage> m_page_standing_in_for_lost_document;
@@ -286,6 +293,9 @@ private:
bool m_has_system_focus { true };
Optional<Web::HTML::CrossProcessId> m_focused_navigable_id;
+
+ // NB: Whether the navigables being removed are the descendants of a removed navigable.
+ bool m_removing_navigable_descendants { false };
};
}
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index 3f03ed51510..8c6e3c11562 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -41,6 +41,7 @@
#include <LibWebView/UserAgent.h>
#include <LibWebView/ViewImplementation.h>
#include <LibWebView/WebContentClient.h>
+#include <LibWebView/WebDriverBiDi.h>
#include <math.h>
namespace WebView {
@@ -51,10 +52,16 @@ static HashMap<u64, ViewImplementation*>& all_views()
return *views;
}
+// NB: WebDriver BiDi names the navigable that is gone a browsing context, whose error code is no such frame.
+static Web::WebDriver::ErrorCode error_code_for_a_navigable_that_is_gone(auto protocol)
+{
+ return protocol == decltype(protocol)::BiDi ? Web::WebDriver::ErrorCode::NoSuchFrame : Web::WebDriver::ErrorCode::NoSuchWindow;
+}
+
static void fail_webdriver_content_commands_after_window_close(auto const& commands)
{
for (auto const& command : commands)
- Application::the().complete_webdriver_content_command(command.key, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "Window closed while executing the command"sv));
+ Application::the().complete_webdriver_content_command(command.key, Web::WebDriver::Error::from_code(error_code_for_a_navigable_that_is_gone(command.value.protocol), "Window closed while executing the command"sv));
}
static u64 s_view_count = 1; // This has to start at 1 for Firefox DevTools.
@@ -106,6 +113,12 @@ ViewImplementation::~ViewImplementation()
reset_spell_checking();
all_views().remove(m_view_id);
+ // NB: WebDriver BiDi may activate another top-level traversable, which must not be this one that is going away.
+ if (!m_window_handle.is_empty() && !m_owner_view_id.has_value()) {
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->top_level_traversable_did_close(m_window_handle);
+ }
+
if (m_top_level_traversable) {
m_top_level_traversable->discard_pending_host();
m_top_level_traversable->discard_representing_pages();
@@ -516,6 +529,21 @@ void ViewImplementation::reload(BypassCache bypass_cache)
dump_session_history("reload-mark-current-entry-reload-pending"sv);
}
+void ViewImplementation::reload_for_webdriver_bidi(BypassCache bypass_cache, Utf16String navigation_id)
+{
+ m_history_visit_transition_for_next_load = HistoryVisitTransition::Reload;
+ if (on_before_browser_initiated_navigation)
+ on_before_browser_initiated_navigation();
+
+ // NB: BiDi reloads the active document, rather than retrying a stopped or failed navigation.
+ m_last_stopped_navigation.clear();
+ prepare_for_navigation_after_crash();
+ set_loading_state(true);
+ traversable().reload(bypass_cache, move(navigation_id));
+ update_navigation_action_state();
+ dump_session_history("reload-mark-current-entry-reload-pending"sv);
+}
+
void ViewImplementation::stop_loading()
{
if (!m_is_loading)
@@ -2760,8 +2788,14 @@ void ViewImplementation::initialize_tab(Web::HTML::VisibilityState system_visibi
if (m_window_handle.is_empty()) {
m_window_handle = generate_random_uuid();
- if (!m_owner_view_id.has_value())
+ if (!m_owner_view_id.has_value()) {
Application::the().notify_webdriver_window_created(m_window_handle);
+
+ // NB: WebDriver BiDi names a top-level traversable by its window handle, so the traversable is reported as
+ // created once it has one.
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->top_level_traversable_did_get_window_handle(*traversable);
+ }
}
prepare_page_for_tab(page());
display_page_changed({});
@@ -2973,7 +3007,12 @@ void ViewImplementation::run_webdriver_content_command(u64 command_id, Web::WebD
run_webdriver_content_command(command_id, navigable_id, name, move(payload), move(arguments));
}
-void ViewImplementation::run_webdriver_content_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments)
+void ViewImplementation::run_webdriver_bidi_content_command(u64 command_id, Web::HTML::CrossProcessId navigable_id, String const& method, JsonValue params)
+{
+ run_webdriver_content_command(command_id, navigable_id, method, move(params), {}, WebDriverProtocol::BiDi);
+}
+
+void ViewImplementation::run_webdriver_content_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments, WebDriverProtocol protocol)
{
if (m_crash_state.has_value() && !m_crash_state->recovery_started) {
Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "WebContent has crashed"sv));
@@ -2988,7 +3027,7 @@ void ViewImplementation::run_webdriver_content_command(u64 command_id, Optional<
// A browsing context is said to be no longer open if its navigable has been destroyed.
navigable = traversable().find(*navigable_id);
if (!navigable.has_value()) {
- Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "Window not found"sv));
+ Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(error_code_for_a_navigable_that_is_gone(protocol), "Window not found"sv));
return;
}
target = traversable().page_hosting(*navigable);
@@ -2997,12 +3036,18 @@ void ViewImplementation::run_webdriver_content_command(u64 command_id, Optional<
// No page holds the navigable's document between the displayed document's unload and the activation of the
// document another page populated to replace it, so the command waits for that document.
if (traversable().is_handing_navigable_to_another_page(*navigable)) {
- m_webdriver_commands_waiting_for_a_document.set(command_id, { navigable_id, name, move(payload), move(arguments) });
+ m_webdriver_commands_waiting_for_a_document.set(command_id, { navigable_id, name, move(payload), move(arguments), protocol });
return;
}
if (!target || !target->is_open()) {
- Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "Window not found"sv));
+ Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(error_code_for_a_navigable_that_is_gone(protocol), "Window not found"sv));
+ return;
+ }
+
+ if (protocol == WebDriverProtocol::BiDi) {
+ m_pending_webdriver_commands.set(command_id, { *target, name, navigable_id, protocol });
+ target->async_run_webdriver_bidi_command(command_id, *navigable_id, name, move(payload));
return;
}
@@ -3017,7 +3062,7 @@ void ViewImplementation::run_webdriver_commands_waiting_for_a_document(Badge<Can
{
auto commands = move(m_webdriver_commands_waiting_for_a_document);
for (auto& [command_id, command] : commands)
- run_webdriver_content_command(command_id, command.navigable_id, command.name, move(command.payload), move(command.arguments));
+ run_webdriver_content_command(command_id, command.navigable_id, command.name, move(command.payload), move(command.arguments), command.protocol);
}
void ViewImplementation::prepare_page_for_navigable(WebContentPage& page)
@@ -3162,7 +3207,7 @@ void ViewImplementation::did_lose_page(Badge<CanonicalTraversable>, WebContentPa
return false;
if (process_lost == WebContentProcessLost::No && complete_webdriver_content_command_after_navigation(command_id, command))
return true;
- Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "Browsing context was discarded while executing the command"sv));
+ Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(error_code_for_a_navigable_that_is_gone(command.protocol), "Browsing context was discarded while executing the command"sv));
return true;
});
}
@@ -3310,6 +3355,12 @@ void ViewImplementation::did_close_browsing_context(Badge<WebContentPage>)
{
reject_pending_selection_requests();
+ // https://html.spec.whatwg.org/multipage/document-sequences.html#destroy-a-top-level-traversable
+ // 6. Invoke WebDriver BiDi navigable destroyed with traversable.
+ auto* webdriver_bidi = WebDriverBiDi::the();
+ if (webdriver_bidi && !m_window_handle.is_empty() && !m_owner_view_id.has_value())
+ webdriver_bidi->navigable_destroyed(traversable());
+
auto window_handle = move(m_window_handle);
// Headless views retain their closed children. Remove the view from routing immediately so a command racing
@@ -3318,8 +3369,11 @@ void ViewImplementation::did_close_browsing_context(Badge<WebContentPage>)
traversable().discard_pending_host();
traversable().discard_representing_pages();
- if (!window_handle.is_empty() && !m_owner_view_id.has_value())
+ if (!window_handle.is_empty() && !m_owner_view_id.has_value()) {
Application::the().notify_webdriver_window_closed(window_handle);
+ if (webdriver_bidi)
+ webdriver_bidi->top_level_traversable_did_close(window_handle);
+ }
auto pending_user_prompt_requests = move(m_pending_webdriver_user_prompt_requests);
for (auto& request : pending_user_prompt_requests)
@@ -3711,6 +3765,8 @@ void ViewImplementation::handle_web_content_process_crash()
auto pending_crash_commands = move(m_pending_webdriver_crash_commands);
for (auto const& command : pending_commands)
Application::the().complete_webdriver_content_command(command.key, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "WebContent crashed while executing the command"sv));
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->top_level_traversable_did_crash(traversable());
auto crashed_during_recovery = m_webdriver_navigation_observation.has_value()
&& m_webdriver_navigation_observation->completion_source == WebDriverNavigationCompletionSource::CrashRecovery;
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index 97ddf4063b8..3bd340b1fa1 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -162,6 +162,7 @@ public:
void load_navigation_error_page(StringView);
void reload(BypassCache = BypassCache::No);
+ void reload_for_webdriver_bidi(BypassCache, Utf16String navigation_id);
void stop_loading();
bool is_loading() const { return m_is_loading; }
// Whether the most recent load ran to completion, rather than being stopped or canceled.
@@ -432,6 +433,8 @@ public:
JsonValue webdriver_session_history() const;
void wait_for_webdriver_navigation_completion(Optional<u64> page_load_timeout, Function<void(Web::WebDriver::Response)>);
void run_webdriver_content_command(u64 command_id, Web::WebDriver::SessionBrowsingContext, String const& name, JsonValue payload, Vector<String> arguments);
+ // https://w3c.github.io/webdriver-bidi/#commands
+ void run_webdriver_bidi_content_command(u64 command_id, Web::HTML::CrossProcessId navigable_id, String const& method, JsonValue params);
void run_webdriver_commands_waiting_for_a_document(Badge<CanonicalTraversable>);
void did_complete_webdriver_content_command(WebContentPage&, u64 command_id, Web::WebDriver::Response);
void did_set_webdriver_current_browsing_context(Badge<WebContentPage>, u64 command_id, Web::HTML::CrossProcessId navigable_id);
@@ -972,10 +975,15 @@ protected:
Function<void(bool)> on_complete;
};
HashMap<u64, PendingClosePreflightRequest> m_pending_close_preflight_requests;
+ enum class WebDriverProtocol : u8 {
+ Classic,
+ BiDi,
+ };
struct PendingWebDriverCommand {
NonnullRefPtr<WebContentPage> page;
String name;
Optional<Web::HTML::CrossProcessId> navigable_id;
+ WebDriverProtocol protocol { WebDriverProtocol::Classic };
};
HashMap<u64, PendingWebDriverCommand> m_pending_webdriver_commands;
HashMap<u64, PendingWebDriverCommand> m_pending_webdriver_crash_commands;
@@ -984,9 +992,10 @@ protected:
String name;
JsonValue payload;
Vector<String> arguments;
+ WebDriverProtocol protocol { WebDriverProtocol::Classic };
};
HashMap<u64, WebDriverCommandWaitingForADocument> m_webdriver_commands_waiting_for_a_document;
- void run_webdriver_content_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments);
+ void run_webdriver_content_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments, WebDriverProtocol = WebDriverProtocol::Classic);
static bool webdriver_content_command_outlives_its_page(StringView name);
bool complete_webdriver_content_command_after_navigation(u64 command_id, PendingWebDriverCommand const&);
void complete_webdriver_content_commands_after_process_replacement(HashMap<u64, PendingWebDriverCommand> const&);
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index b6dd1d267fe..2930cfbaa96 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -38,6 +38,7 @@
#include <LibWebView/WebContentClient.h>
#include <LibWebView/WebContentPage.h>
#include <LibWebView/WebContentTestClient.h>
+#include <LibWebView/WebDriverBiDi.h>
#include <LibWebView/WebUI.h>
#include <LibWebView/WorkerProcessManager.h>
@@ -1346,6 +1347,18 @@ void WebContentPage::webdriver_command_complete(u64 command_id, Web::WebDriver::
view().did_complete_webdriver_content_command(*this, command_id, move(response));
}
+void WebContentPage::webdriver_bidi_event(Web::HTML::CrossProcessId navigable_id, String name, JsonValue params)
+{
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->did_receive_event(*this, navigable_id, name, move(params));
+}
+
+void WebContentPage::webdriver_bidi_navigation_event(Web::HTML::CrossProcessId navigable_id, String name, Optional<Utf16String> navigation_id, URL::URL url)
+{
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->did_receive_navigation_event(*this, navigable_id, name, move(navigation_id), move(url));
+}
+
void WebContentPage::did_update_resource_count(i32 count_waiting)
{
if (displays_tab()) {
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index 889a86b4a88..0b502616da8 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -239,6 +239,8 @@ private:
virtual void webdriver_user_prompt_handling_complete(u64 request_id, Web::WebDriver::Response response) override;
virtual void webdriver_did_set_current_browsing_context(u64 command_id, Web::HTML::CrossProcessId navigable_id) override;
virtual void webdriver_command_complete(u64 command_id, Web::WebDriver::Response response) override;
+ virtual void webdriver_bidi_event(Web::HTML::CrossProcessId navigable_id, String name, JsonValue params) override;
+ virtual void webdriver_bidi_navigation_event(Web::HTML::CrossProcessId navigable_id, String name, Optional<Utf16String> navigation_id, URL::URL url) override;
virtual void did_update_resource_count(i32 count_waiting) override;
virtual void did_request_restore_window() override;
virtual void did_request_reposition_window(Gfx::IntPoint position, u64 completion_id) override;
diff --git a/Libraries/LibWebView/WebDriverBiDi.cpp b/Libraries/LibWebView/WebDriverBiDi.cpp
new file mode 100644
index 00000000000..1713d272e0c
--- /dev/null
+++ b/Libraries/LibWebView/WebDriverBiDi.cpp
@@ -0,0 +1,1934 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/AnyOf.h>
+#include <AK/JsonArray.h>
+#include <AK/QuickSort.h>
+#include <AK/Random.h>
+#include <AK/ScopeGuard.h>
+#include <AK/Time.h>
+#include <AK/WeakPtr.h>
+#include <LibCore/EventLoop.h>
+#include <LibURL/Parser.h>
+#include <LibWebView/CanonicalNavigable.h>
+#include <LibWebView/CanonicalTraversable.h>
+#include <LibWebView/ViewImplementation.h>
+#include <LibWebView/WebContentClient.h>
+#include <LibWebView/WebContentPage.h>
+#include <LibWebView/WebDriverBiDi.h>
+#include <LibWebView/WebDriverBrowserConnection.h>
+
+// Failures complete the command rather than propagate, so this macro may only be used in functions that take its
+// completion as on_complete and return nothing.
+#define TRY_OR_COMPLETE(expression) \
+ ({ \
+ /* Ignore -Wshadow to allow nesting the macro. */ \
+ AK_IGNORE_DIAGNOSTIC("-Wshadow", \
+ auto&& _temporary_result = (expression)); \
+ static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
+ "Do not return a reference from a fallible expression"); \
+ if (_temporary_result.is_error()) [[unlikely]] { \
+ on_complete(_temporary_result.release_error()); \
+ return; \
+ } \
+ _temporary_result.release_value(); \
+ })
+
+namespace WebView {
+
+using Web::WebDriver::as_js_uint;
+
+WebDriverBiDi* WebDriverBiDi::s_the { nullptr };
+
+// NB: The ids of the commands this object sends to processes hosting navigables are apart from those of the commands
+// WebDriver sends.
+static constexpr u64 FIRST_CONTENT_COMMAND_ID = 1ull << 62;
+
+// https://w3c.github.io/webdriver-bidi/#default-user-context
+// FIXME: Support user contexts other than the default user context.
+static constexpr auto DEFAULT_USER_CONTEXT_ID = "default"sv;
+
+static Web::WebDriver::Error invalid_argument(StringView message)
+{
+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, message);
+}
+
+static Web::WebDriver::Error no_such_frame()
+{
+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, "Browsing context not found"sv);
+}
+
+static ErrorOr<String, Web::WebDriver::Error> get_string(JsonObject const& params, StringView name)
+{
+ auto value = params.get(name);
+ if (!value.has_value() || !value->is_string())
+ return invalid_argument(MUST(String::formatted("Parameter '{}' must be a string", name)));
+ return value->as_string();
+}
+
+static ErrorOr<Optional<String>, Web::WebDriver::Error> get_optional_string(JsonObject const& params, StringView name)
+{
+ if (!params.has(name))
+ return Optional<String> {};
+ return TRY(get_string(params, name));
+}
+
+static ErrorOr<Optional<bool>, Web::WebDriver::Error> get_optional_bool(JsonObject const& params, StringView name)
+{
+ auto value = params.get(name);
+ if (!value.has_value())
+ return Optional<bool> {};
+ if (!value->is_bool())
+ return invalid_argument(MUST(String::formatted("Parameter '{}' must be a boolean", name)));
+ return value->as_bool();
+}
+
+static ErrorOr<Optional<Vector<String>>, Web::WebDriver::Error> get_optional_non_empty_list_of_strings(JsonObject const& params, StringView name)
+{
+ auto value = params.get(name);
+ if (!value.has_value())
+ return Optional<Vector<String>> {};
+ if (!value->is_array() || value->as_array().is_empty())
+ return invalid_argument(MUST(String::formatted("Parameter '{}' must be a non-empty list of strings", name)));
+
+ Vector<String> result;
+ for (auto const& item : value->as_array().values()) {
+ if (!item.is_string())
+ return invalid_argument(MUST(String::formatted("Parameter '{}' must be a non-empty list of strings", name)));
+ result.append(item.as_string());
+ }
+ return result;
+}
+
+WebDriverBiDi::WebDriverBiDi(WebDriverBrowserConnection& connection)
+ : m_connection(connection)
+ , m_next_content_command_id(FIRST_CONTENT_COMMAND_ID)
+{
+ VERIFY(!s_the);
+ s_the = this;
+}
+
+WebDriverBiDi::~WebDriverBiDi()
+{
+ s_the = nullptr;
+
+ // NB: Web content runs no WebDriver BiDi steps once the session is gone.
+ if (m_session_state.is_active) {
+ WebContentClient::for_each_client([&](WebContentClient& client) {
+ client.async_set_webdriver_bidi_session_state({});
+ return IterationDecision::Continue;
+ });
+ }
+}
+
+void WebDriverBiDi::complete_command(u64 command_id, Web::WebDriver::Response response)
+{
+ m_connection.async_command_complete(command_id, move(response));
+}
+
+bool WebDriverBiDi::did_complete_content_command(u64 command_id, Web::WebDriver::Response& response)
+{
+ auto on_complete = m_pending_content_commands.take(command_id);
+ if (!on_complete.has_value())
+ return false;
+
+ on_complete.value()(move(response));
+ return true;
+}
+
+void WebDriverBiDi::ensure_session_is_active()
+{
+ if (!m_session_state.is_active)
+ push_session_state();
+}
+
+void WebDriverBiDi::push_session_state()
+{
+ m_session_state.is_active = true;
+ m_session_state.enabled_events.clear_with_capacity();
+ for (auto const& event_name : m_enabled_events)
+ m_session_state.enabled_events.append(event_name);
+
+ WebContentClient::for_each_client([&](WebContentClient& client) {
+ client.async_set_webdriver_bidi_session_state(m_session_state);
+ return IterationDecision::Continue;
+ });
+}
+
+void WebDriverBiDi::set_enabled_events(Vector<String> const& event_names)
+{
+ m_enabled_events.clear();
+ for (auto const& event_name : event_names)
+ m_enabled_events.set(event_name);
+
+ push_session_state();
+}
+
+// https://w3c.github.io/webdriver-bidi/#type-browsingContext-Browsingcontext
+// For navigables with an associated WebDriver window handle the navigable id must be the same as the window handle.
+String WebDriverBiDi::navigable_id(CanonicalNavigable const& navigable)
+{
+ if (navigable.is_top_level_traversable()) {
+ if (auto view = static_cast<CanonicalTraversable const&>(navigable).view(); view.has_value() && !view->handle().is_empty())
+ return view->handle();
+ }
+
+ // NB: This is how WebContent names a frame to WebDriver.
+ return MUST(String::formatted("{}-{}", navigable.id().namespace_id, navigable.id().local_id));
+}
+
+static bool is_top_level_traversable_of_a_window(ViewImplementation const& view)
+{
+ return !view.owner_view_id().has_value() && view.has_traversable() && !view.handle().is_empty();
+}
+
+static Vector<CanonicalTraversable&> all_top_level_traversables()
+{
+ // NB: The traversables are in the order they were created in, which is the order of their views' ids.
+ Vector<ViewImplementation*> views;
+ ViewImplementation::for_each_view([&](ViewImplementation& view) {
+ if (is_top_level_traversable_of_a_window(view))
+ views.append(&view);
+ return IterationDecision::Continue;
+ });
+ quick_sort(views, [](auto const* a, auto const* b) { return a->view_id() < b->view_id(); });
+
+ Vector<CanonicalTraversable&> traversables;
+ for (auto* view : views)
+ traversables.append(view->traversable());
+ return traversables;
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-a-navigable
+static ErrorOr<CanonicalNavigable*, Web::WebDriver::Error> get_a_navigable(StringView navigable_id)
+{
+ // 1. If navigable id is null, return success with data null.
+
+ // 2. If there is no navigable with navigable id navigable id return error with error code no such frame
+ // 3. Let navigable be the navigable with id navigable id.
+ // 4. Return success with data navigable.
+ if (auto view = ViewImplementation::find_view_by_handle(navigable_id); view.has_value() && is_top_level_traversable_of_a_window(*view))
+ return &view->traversable();
+
+ auto parts = navigable_id.split_view('-');
+ if (parts.size() != 2)
+ return no_such_frame();
+
+ auto namespace_id = parts[0].to_number<u64>();
+ auto local_id = parts[1].to_number<u64>();
+ if (!namespace_id.has_value() || !local_id.has_value())
+ return no_such_frame();
+
+ Web::HTML::CrossProcessId id { .namespace_id = *namespace_id, .local_id = *local_id };
+ auto* traversable = CanonicalTraversable::traversable_containing(id);
+ if (!traversable)
+ return no_such_frame();
+
+ auto view = traversable->view();
+ if (!view.has_value() || !is_top_level_traversable_of_a_window(*view))
+ return no_such_frame();
+
+ auto navigable = traversable->find(id);
+ if (!navigable.has_value() || navigable->is_top_level_traversable())
+ return no_such_frame();
+
+ return &navigable.value();
+}
+
+static ErrorOr<CanonicalTraversable*, Web::WebDriver::Error> get_a_top_level_traversable(StringView navigable_id)
+{
+ auto* navigable = TRY(get_a_navigable(navigable_id));
+ if (!navigable->is_top_level_traversable())
+ return invalid_argument("Browsing context is not a top-level traversable"sv);
+ return static_cast<CanonicalTraversable*>(navigable);
+}
+
+void WebDriverBiDi::emit_event(StringView name, JsonValue params, Vector<String> top_level_traversable_ids)
+{
+ m_connection.async_bidi_event(MUST(String::from_utf8(name)), move(params), move(top_level_traversable_ids), { MUST(String::from_utf8(DEFAULT_USER_CONTEXT_ID)) });
+}
+
+void WebDriverBiDi::emit_event_for_navigable(StringView name, JsonValue params, CanonicalNavigable const& navigable)
+{
+ emit_event(name, move(params), { navigable_id(navigable.top_level_traversable()) });
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-the-navigable-info
+JsonObject WebDriverBiDi::get_the_navigable_info(CanonicalNavigable const& navigable, Optional<u64> max_depth, bool include_parent_id) const
+{
+ // 1. Let navigable id be the navigable id for navigable.
+ auto id = navigable_id(navigable);
+
+ // 2. Let parent navigable be navigable's parent.
+ auto const* parent_navigable = navigable.parent();
+
+ // 3. If parent navigable is not null let parent id be the navigable id of parent navigable. Otherwise let parent id
+ // be null.
+ JsonValue parent_id;
+ if (parent_navigable)
+ parent_id = navigable_id(*parent_navigable);
+
+ // 4. Let document be navigable's active document.
+ // 5. Let url be the result of running the URL serializer, given document's URL.
+ auto url = navigable.active_document_url().serialize();
+
+ // 6. Let child infos be null.
+ JsonValue child_infos;
+
+ // 7. If max depth is null, or max depth is greater than 0:
+ if (!max_depth.has_value() || *max_depth > 0) {
+ // 1. Let child navigables be get the child navigables given navigable.
+ // 2. Let child depth be max depth - 1 if max depth is not null, or null otherwise.
+ Optional<u64> child_depth;
+ if (max_depth.has_value())
+ child_depth = *max_depth - 1;
+
+ // 3. Set child infos to an empty list.
+ JsonArray infos;
+
+ // 4. For each child navigable of child navigables:
+ for (auto const& child_navigable : navigable.children()) {
+ // 1. Let info be the result of get the navigable info given child navigable, child depth, and false.
+ // 2. Append info to child infos
+ infos.must_append(get_the_navigable_info(*child_navigable, child_depth, false));
+ }
+ child_infos = move(infos);
+ }
+
+ // 8. Let user context be navigable's associated user context.
+
+ // 9. Let opener id be the navigable id for navigable's original opener, if navigable's original opener is not null,
+ // and null otherwise.
+ JsonValue opener_id;
+ if (auto opener = m_original_openers.get(navigable.id()); opener.has_value())
+ opener_id = *opener;
+
+ // 10. Let top-level traversable be navigable's top-level traversable.
+ // 11. Let client window id be the client window id for top-level traversable's associated client window.
+ // FIXME: Name the OS window a tab is in, rather than the tab.
+ auto client_window_id = navigable_id(navigable.top_level_traversable());
+
+ // 12. Let navigable info be a map matching the browsingContext.Info production with the context field set to
+ // navigable id, the parent field set to parent id if include parent id is true, or unset otherwise, the url
+ // field set to url, the userContext field set to user context's user context id, originalOpener field set to
+ // opener id, the children field set to child infos, and the clientWindow field set to client window id.
+ JsonObject navigable_info;
+ navigable_info.set("context"sv, move(id));
+ if (include_parent_id)
+ navigable_info.set("parent"sv, move(parent_id));
+ navigable_info.set("url"sv, move(url));
+ navigable_info.set("userContext"sv, DEFAULT_USER_CONTEXT_ID);
+ navigable_info.set("originalOpener"sv, move(opener_id));
+ navigable_info.set("children"sv, move(child_infos));
+ navigable_info.set("clientWindow"sv, move(client_window_id));
+
+ // 13. Return navigable info.
+ return navigable_info;
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-the-navigation-info
+JsonObject WebDriverBiDi::get_the_navigation_info(CanonicalNavigable const& navigable, NavigationStatus const& navigation_status) const
+{
+ // 1. Let navigable id be the navigable id for navigable.
+ // 2. Let navigation id be navigation status's id.
+ // 3. Let timestamp be a time value representing the current date and time in UTC.
+ // 4. Let url be navigation status's url.
+ // 5. Let user context id be the user context id of navigable's associated user context.
+ // 6. Return a map matching the browsingContext.NavigationInfo production, with the context field set to navigable
+ // id, the navigation field set to navigation id, the timestamp field set to timestamp, the url field set to the
+ // result of the URL serializer given url, and the userContext field set to user context id.
+ JsonObject info;
+ info.set("context"sv, navigable_id(navigable));
+ if (navigation_status.id.has_value())
+ info.set("navigation"sv, navigation_status.id->to_utf8());
+ else
+ info.set("navigation"sv, JsonValue {});
+ info.set("timestamp"sv, UnixDateTime::now().milliseconds_since_epoch());
+ info.set("url"sv, navigation_status.url.serialize());
+ info.set("userContext"sv, DEFAULT_USER_CONTEXT_ID);
+ return info;
+}
+
+// https://w3c.github.io/webdriver-bidi/#await
+void WebDriverBiDi::await(Vector<StringView> events, Web::HTML::CrossProcessId navigable_id, Utf16String const& resume_id, ResumeSteps algorithm)
+{
+ // 1. Pause the execution of algorithm.
+ // 2. Assert: wait queue does not contain resume id.
+ VERIFY(!m_wait_queue.contains(resume_id));
+
+ // 3. Set wait queue[resume id] to (events, algorithm).
+ m_wait_queue.set(resume_id, { move(events), navigable_id, move(algorithm) });
+}
+
+// https://w3c.github.io/webdriver-bidi/#resume
+void WebDriverBiDi::resume(StringView name, Web::HTML::CrossProcessId navigable_id, Utf16String const& id, NavigationStatus const& parameters)
+{
+ // 1. If wait queue does not contain id, return.
+ // NB: The events of another navigable, which another process may report, do not resume the steps.
+ auto waiter = m_wait_queue.find(id);
+ if (waiter == m_wait_queue.end() || waiter->value.navigable_id != navigable_id)
+ return;
+
+ // 2. Let (events, algorithm) be wait queue[id]
+ // 3. For each event in events:
+ for (auto event : waiter->value.events) {
+ // 1. If event equals name:
+ if (event == name) {
+ // 1. Remove id from wait queue.
+ auto algorithm = move(waiter->value.algorithm);
+ m_wait_queue.remove(waiter);
+
+ // 2. Resume running the steps in algorithm from the point at which they were paused, passing name and
+ // parameters as the result of the await.
+ algorithm(name, parameters);
+ return;
+ }
+ }
+}
+
+void WebDriverBiDi::fail_navigations_of(Function<bool(Web::HTML::CrossProcessId)> const& is_affected_navigable)
+{
+ Vector<Utf16String> navigation_ids;
+ for (auto const& [navigation_id, waiter] : m_wait_queue) {
+ if (is_affected_navigable(waiter.navigable_id))
+ navigation_ids.append(navigation_id);
+ }
+ for (auto const& navigation_id : navigation_ids) {
+ auto waiter = m_wait_queue.take(navigation_id);
+ if (!waiter.has_value())
+ continue;
+ waiter->algorithm("navigation failed"sv, { .id = navigation_id, .status = NavigationStatusType::Canceled, .url = {} });
+ }
+
+ Vector<Web::HTML::CrossProcessId> reloading_navigable_ids;
+ for (auto const& [navigable_id, waiter] : m_reload_waiters) {
+ if (is_affected_navigable(navigable_id))
+ reloading_navigable_ids.append(navigable_id);
+ }
+ for (auto const& navigable_id : reloading_navigable_ids) {
+ if (auto waiter = m_reload_waiters.take(navigable_id); waiter.has_value())
+ waiter->on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Navigation failed"sv));
+ }
+}
+
+static bool navigable_exists(Web::HTML::CrossProcessId navigable_id)
+{
+ return CanonicalTraversable::traversable_containing(navigable_id) != nullptr;
+}
+
+// NB: This runs once the navigables that are going away are removed.
+void WebDriverBiDi::remove_state_of_removed_navigables()
+{
+ fail_navigations_of([](auto navigable_id) { return !navigable_exists(navigable_id); });
+
+ m_destroyed_navigables.remove_all_matching([](auto navigable_id) { return !navigable_exists(navigable_id); });
+ m_closing_traversable_infos.remove_all_matching([](auto navigable_id, auto const&) { return !navigable_exists(navigable_id); });
+}
+
+void WebDriverBiDi::top_level_traversable_did_crash(CanonicalTraversable const& traversable)
+{
+ fail_navigations_of([&](auto navigable_id) { return CanonicalTraversable::traversable_containing(navigable_id) == &traversable; });
+}
+
+// https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigable-created
+void WebDriverBiDi::navigable_created(CanonicalNavigable const& navigable, Optional<CanonicalNavigable const&> opener_navigable)
+{
+ // 1. Set navigable's original opener to opener navigable.
+ if (opener_navigable.has_value())
+ m_original_openers.set(navigable.id(), navigable_id(*opener_navigable));
+
+ // NB: A top-level traversable is named by the window handle of its view, which it does not have yet.
+ if (navigable.is_top_level_traversable())
+ return;
+
+ // 2. If the navigable cache behavior with navigable is "bypass", then perform implementation-defined steps to
+ // disable any implementation-specific resource caches for network requests originating from navigable.
+
+ // 3. Let related navigables be a set containing navigable.
+ // 4. For each session in the set of sessions for which an event is enabled given "browsingContext.contextCreated"
+ // and related navigables:
+ if (!is_event_enabled("browsingContext.contextCreated"sv))
+ return;
+
+ // 1. Emit a context created event given session, navigable, and has planned navigation.
+ // https://w3c.github.io/webdriver-bidi/#emit-a-context-created-event
+ auto params = get_the_navigable_info(navigable, 0, true);
+ params.set("hasPlannedNavigation"sv, false);
+ emit_event_for_navigable("browsingContext.contextCreated"sv, move(params), navigable);
+}
+
+void WebDriverBiDi::top_level_traversable_did_get_window_handle(CanonicalTraversable const& traversable)
+{
+ if (!is_event_enabled("browsingContext.contextCreated"sv))
+ return;
+
+ // https://w3c.github.io/webdriver-bidi/#emit-a-context-created-event
+ auto params = get_the_navigable_info(traversable, 0, true);
+ params.set("hasPlannedNavigation"sv, false);
+ emit_event_for_navigable("browsingContext.contextCreated"sv, move(params), traversable);
+}
+
+// https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigable-destroyed
+void WebDriverBiDi::navigable_destroyed(CanonicalNavigable const& navigable)
+{
+ // NB: The navigable's info, which names its original opener, is reported before the navigable is forgotten.
+ ScopeGuard forget_original_opener = [&] { m_original_openers.remove(navigable.id()); };
+
+ Core::deferred_invoke([] {
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->remove_state_of_removed_navigables();
+ });
+
+ if (m_destroyed_navigables.remove(navigable.id()))
+ return;
+
+ if (!is_event_enabled("browsingContext.contextDestroyed"sv)) {
+ m_closing_traversable_infos.remove(navigable.id());
+ return;
+ }
+
+ // 1. Let params be the result of get the navigable info, given navigable, null, and true.
+ auto params = m_closing_traversable_infos.take(navigable.id()).value_or_lazy_evaluated([&] {
+ return get_the_navigable_info(navigable, {}, true);
+ });
+
+ // 2. Let body be a map matching the browsingContext.ContextDestroyed production, with the params field set to
+ // params.
+ // 3. Let related navigables be a set containing navigable's parent, if that is not null, or an empty set otherwise.
+ // INTEROP: The destruction of a top-level traversable is reported to the sessions subscribed to its events, which
+ // is what other implementations do, so the related navigables contain the traversable itself.
+ Vector<String> top_level_traversable_ids;
+ top_level_traversable_ids.append(navigable_id(navigable.top_level_traversable()));
+
+ // 4. For each session in the set of sessions for which an event is enabled given
+ // "browsingContext.contextDestroyed" and related navigables:
+ // 1. Emit an event with session and body.
+ emit_event("browsingContext.contextDestroyed"sv, move(params), move(top_level_traversable_ids));
+}
+
+// NB: The navigables of a closing top-level traversable are removed before the traversable is destroyed, which reports
+// its info as it was.
+void WebDriverBiDi::top_level_traversable_is_closing(CanonicalNavigable const& traversable)
+{
+ if (!is_event_enabled("browsingContext.contextDestroyed"sv) || m_closing_traversable_infos.contains(traversable.id()))
+ return;
+ m_closing_traversable_infos.set(traversable.id(), get_the_navigable_info(traversable, {}, true));
+}
+
+void WebDriverBiDi::top_level_traversable_did_close(String const& window_handle)
+{
+ auto os_window = os_window_of(window_handle);
+ m_tab_windows.remove(window_handle);
+ m_viewport_defaults.remove(window_handle);
+ m_css_viewport_overrides.remove(window_handle);
+ remove_state_of_removed_navigables();
+
+ // NB: Closing the focused top-level traversable activates the last other one of its OS window, or the last other
+ // one there is, the way a browser activates another tab or window.
+ auto traversables = all_top_level_traversables();
+ if (!traversables.is_empty() && !any_of(traversables, [](auto const& traversable) { return traversable.has_system_focus(); })) {
+ auto const* next_traversable = &traversables.last();
+ for (auto const& traversable : traversables) {
+ if (os_window_of(navigable_id(traversable)) == os_window)
+ next_traversable = &traversable;
+ }
+ JsonObject params;
+ params.set("context"sv, navigable_id(*next_traversable));
+ browsing_context_activate(params, [](auto) { });
+ }
+
+ if (auto close_commands = m_pending_close_commands.take(window_handle); close_commands.has_value()) {
+ for (auto& on_complete : *close_commands)
+ on_complete(JsonValue {});
+ }
+}
+
+void WebDriverBiDi::navigation_superseded_reload(CanonicalNavigable const& navigable)
+{
+ if (auto waiter = m_reload_waiters.take(navigable.id()); waiter.has_value())
+ waiter->on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Navigation was canceled"sv));
+}
+
+void WebDriverBiDi::reload_did_not_apply(CanonicalTraversable const& traversable, Optional<Utf16String> const& navigation_id)
+{
+ auto it = m_reload_waiters.find(traversable.id());
+ if (it == m_reload_waiters.end() || it->value.navigation_id != navigation_id)
+ return;
+ if (auto waiter = m_reload_waiters.take(traversable.id()); waiter.has_value())
+ waiter->on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Navigation was canceled"sv));
+}
+
+// https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigation-started
+void WebDriverBiDi::navigation_started(CanonicalNavigable const& navigable, NavigationStatus const& navigation_status)
+{
+ // 1. Let params be the result of get the navigation info given navigable and navigation status.
+ // 2. Let body be a map matching the browsingContext.NavigationStarted production, with the params field set to
+ // params.
+ auto params = get_the_navigation_info(navigable, navigation_status);
+
+ // 3. Let navigation id be navigation status's id.
+ // 4. Let related navigables be a set containing navigable.
+ // 5. Resume with "navigation started", navigation id, and navigation status.
+ // 6. For each session in the set of sessions for which an event is enabled given
+ // "browsingContext.navigationStarted" and related navigables:
+ // 1. Emit an event with session and body.
+ // NB: The event is emitted before resuming, as the steps resumed may complete a command, whose response the local
+ // end expects after the event.
+ if (is_event_enabled("browsingContext.navigationStarted"sv))
+ emit_event_for_navigable("browsingContext.navigationStarted"sv, move(params), navigable);
+ if (navigation_status.id.has_value())
+ resume("navigation started"sv, navigable.id(), *navigation_status.id, navigation_status);
+}
+
+// https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigation-failed
+void WebDriverBiDi::navigation_failed(CanonicalNavigable const& navigable, NavigationStatus const& navigation_status)
+{
+ // 1. Let params be the result of get the navigation info given navigable and navigation status.
+ // 2. Let body be a map matching the browsingContext.NavigationFailed production, with the params field set to
+ // params.
+ auto params = get_the_navigation_info(navigable, navigation_status);
+
+ // 3. Let navigation id be navigation status's id.
+ // 4. Let related navigables be a set containing navigable.
+ // 5. Resume with "navigation failed", navigation id, and navigation status.
+ // 6. For each session in the set of sessions for which an event is enabled given
+ // "browsingContext.navigationFailed" and related navigables:
+ // 1. Emit an event with session and body.
+ // NB: The event is emitted before resuming, as the steps resumed may complete a command, whose response the local
+ // end expects after the event.
+ if (is_event_enabled("browsingContext.navigationFailed"sv))
+ emit_event_for_navigable("browsingContext.navigationFailed"sv, move(params), navigable);
+ if (navigation_status.id.has_value())
+ resume("navigation failed"sv, navigable.id(), *navigation_status.id, navigation_status);
+}
+
+void WebDriverBiDi::did_receive_navigation_event(WebContentPage& page, Web::HTML::CrossProcessId navigable_id, String const& name, Optional<Utf16String> navigation_id, URL::URL url)
+{
+ // NB: A process hosting web content only reports on the navigables it hosts.
+ auto navigable = page.hosted_navigable(navigable_id);
+ if (!navigable.has_value())
+ return;
+
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigable-destroyed
+ // NB: The process hosting the container of a child navigable reports its destruction before the navigable and its
+ // descendants are removed, which reports them no more.
+ if (name == "browsingContext.contextDestroyed"sv) {
+ if (navigable->is_top_level_traversable())
+ return;
+ navigable_destroyed(*navigable);
+ Function<void(CanonicalNavigable const&)> mark_as_destroyed = [&](CanonicalNavigable const& destroyed_navigable) {
+ m_destroyed_navigables.set(destroyed_navigable.id());
+ for (auto const& child : destroyed_navigable.children())
+ mark_as_destroyed(*child);
+ };
+ mark_as_destroyed(*navigable);
+ return;
+ }
+
+ // https://w3c.github.io/webdriver-bidi/#event-browsingContext-historyUpdated
+ if (name == "browsingContext.historyUpdated"sv) {
+ if (!is_event_enabled(name))
+ return;
+
+ // 1. Let url be the result of running the URL serializer, given navigable's active browsing context's active
+ // document's URL.
+ // 2. Let user context id be the user context id of navigable's associated user context.
+ // 3. Let timestamp be a time value representing the current date and time in UTC.
+ // 4. Let params be a map matching the browsingContext.HistoryUpdatedParameters production, with the url field
+ // set to url, the timestamp field set to timestamp, the context field set to navigable's navigable id and
+ // the userContext field set to user context id.
+ JsonObject params;
+ params.set("context"sv, WebDriverBiDi::navigable_id(*navigable));
+ params.set("timestamp"sv, UnixDateTime::now().milliseconds_since_epoch());
+ params.set("url"sv, url.serialize());
+ params.set("userContext"sv, DEFAULT_USER_CONTEXT_ID);
+
+ // 5. Let body be a map matching the browsingContext.HistoryUpdated production, with the params field set to
+ // params.
+ // 6. Let related browsing contexts be a set containing navigable's active browsing context.
+ // 7. For each session in the set of sessions for which an event is enabled given
+ // "browsingContext.historyUpdated" and related browsing contexts:
+ // 1. Emit an event with session and body.
+ emit_event_for_navigable(name, move(params), *navigable);
+ return;
+ }
+
+ // NB: These are the events whose triggers run in the process hosting a navigable's active document.
+ struct NavigationEvent {
+ StringView event_name;
+ StringView resume_name;
+ NavigationStatusType status;
+ };
+ static constexpr auto navigation_events = to_array<NavigationEvent>({
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigation-started
+ { "browsingContext.navigationStarted"sv, "navigation started"sv, NavigationStatusType::Pending },
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-fragment-navigated
+ { "browsingContext.fragmentNavigated"sv, "fragment navigated"sv, NavigationStatusType::Complete },
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigation-committed
+ { "browsingContext.navigationCommitted"sv, "navigation committed"sv, NavigationStatusType::Pending },
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-dom-content-loaded
+ { "browsingContext.domContentLoaded"sv, "domContentLoaded"sv, NavigationStatusType::Pending },
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-load-complete
+ { "browsingContext.load"sv, "load"sv, NavigationStatusType::Complete },
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigation-aborted
+ { "browsingContext.navigationAborted"sv, "navigation aborted"sv, NavigationStatusType::Canceled },
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigation-failed
+ { "browsingContext.navigationFailed"sv, "navigation failed"sv, NavigationStatusType::Canceled },
+ });
+
+ NavigationEvent const* event = nullptr;
+ for (auto const& navigation_event : navigation_events) {
+ if (navigation_event.event_name == name)
+ event = &navigation_event;
+ }
+ if (!event)
+ return;
+
+ NavigationStatus navigation_status { .id = move(navigation_id), .status = event->status, .url = move(url) };
+
+ // 1. Let params be the result of get the navigation info given navigable and navigation status.
+ auto params = get_the_navigation_info(*navigable, navigation_status);
+
+ // 2. Let navigation id be navigation status's id.
+ // 3. Let related navigables be a set containing navigable.
+ // 4. Resume with the event's name, navigation id, and navigation status.
+ // 5. For each session in the set of sessions for which an event is enabled given the event's name and related
+ // navigables:
+ // 1. Emit an event with session and body.
+ // NB: The event is emitted before resuming, as the steps resumed may complete a command, whose response the local
+ // end expects after the event.
+ if (is_event_enabled(event->event_name))
+ emit_event_for_navigable(event->event_name, move(params), *navigable);
+ if (navigation_status.id.has_value())
+ resume(event->resume_name, navigable->id(), *navigation_status.id, navigation_status);
+
+ // NB: Events from an older document or a different navigation cannot complete this reload.
+ if (auto waiter = m_reload_waiters.find(navigable->id()); waiter != m_reload_waiters.end() && navigation_status.id == waiter->value.navigation_id) {
+ auto failed = name.is_one_of("browsingContext.navigationAborted"sv, "browsingContext.navigationFailed"sv);
+ auto wait_condition = waiter->value.wait_condition;
+ auto reached = (wait_condition == WaitCondition::Committed && name == "browsingContext.navigationCommitted"sv)
+ || (wait_condition == WaitCondition::Interactive && name == "browsingContext.domContentLoaded"sv)
+ || (wait_condition == WaitCondition::Complete && name == "browsingContext.load"sv);
+
+ if (failed || reached) {
+ auto on_complete = move(waiter->value.on_complete);
+ m_reload_waiters.remove(waiter);
+
+ if (failed) {
+ on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Navigation failed"sv));
+ return;
+ }
+
+ JsonObject body;
+ if (navigation_status.id.has_value())
+ body.set("navigation"sv, navigation_status.id->to_utf8());
+ else
+ body.set("navigation"sv, JsonValue {});
+ body.set("url"sv, navigation_status.url.serialize());
+ on_complete(JsonValue { move(body) });
+ }
+ }
+}
+
+void WebDriverBiDi::did_receive_event(WebContentPage& page, Web::HTML::CrossProcessId navigable_id, String const& name, JsonValue params)
+{
+ // NB: A process hosting web content only reports on the navigables it hosts, and only the events that run there.
+ // The realms of a closing traversable's navigables are destroyed after the navigables are removed, and they
+ // are reported for the traversable instead.
+ auto navigable = page.hosted_navigable(navigable_id);
+ if (!navigable.has_value() && name == "script.realmDestroyed"sv)
+ navigable = page.traversable();
+ if (!navigable.has_value())
+ return;
+
+ static constexpr auto content_events = to_array<StringView>({
+ "log.entryAdded"sv,
+ "script.message"sv,
+ "script.realmCreated"sv,
+ "script.realmDestroyed"sv,
+ });
+ if (!any_of(content_events, [&](auto event_name) { return event_name == name; }))
+ return;
+
+ // NB: WebDriver buffers the log events that no subscription enables.
+ if (!is_event_enabled(name) && name != "log.entryAdded"sv)
+ return;
+
+ // NB: The navigable an event names is the navigable the process reported it for, which the browser process names
+ // itself, so that a process cannot attribute an event to a navigable it does not host.
+ if (!params.is_object())
+ return;
+ auto set_context = [&](JsonObject& object) {
+ if (object.has("context"sv))
+ object.set("context"sv, WebDriverBiDi::navigable_id(*navigable));
+ };
+ if (name.is_one_of("log.entryAdded"sv, "script.message"sv)) {
+ if (auto source = params.as_object().get_object("source"sv); source.has_value())
+ set_context(*source);
+ } else if (name == "script.realmCreated"sv) {
+ set_context(params.as_object());
+ }
+
+ emit_event_for_navigable(name, move(params), *navigable);
+}
+
+void WebDriverBiDi::get_top_level_traversables(u64 command_id, Vector<String> const& navigable_ids)
+{
+ // https://w3c.github.io/webdriver-bidi/#get-valid-navigables-by-ids
+ // https://w3c.github.io/webdriver-bidi/#get-top-level-traversables
+ HashTable<String> seen;
+ JsonArray result;
+
+ for (auto const& id : navigable_ids) {
+ auto navigable = get_a_navigable(id);
+ if (navigable.is_error()) {
+ complete_command(command_id, navigable.release_error());
+ return;
+ }
+
+ auto top_level_traversable_id = navigable_id(navigable.value()->top_level_traversable());
+ if (seen.set(top_level_traversable_id) == HashSetResult::InsertedNewEntry)
+ result.must_append(move(top_level_traversable_id));
+ }
+
+ complete_command(command_id, JsonValue { move(result) });
+}
+
+void WebDriverBiDi::run_subscribe_steps(u64 command_id, String const& event_name, Vector<String> const& top_level_traversable_ids)
+{
+ // https://w3c.github.io/webdriver-bidi/#event-browsingContext-contextCreated
+ if (event_name == "browsingContext.contextCreated"sv) {
+ JsonArray events;
+
+ // https://w3c.github.io/webdriver-bidi/#recursively-emit-context-created-events
+ Function<void(CanonicalNavigable const&)> recursively_emit_context_created_events = [&](CanonicalNavigable const& navigable) {
+ // 1. Emit a context created event with session, navigable, and false.
+ auto params = get_the_navigable_info(navigable, 0, true);
+ params.set("hasPlannedNavigation"sv, false);
+
+ JsonObject event;
+ event.set("method"sv, "browsingContext.contextCreated"sv);
+ event.set("params"sv, move(params));
+ events.must_append(move(event));
+
+ // 2. For each child navigable, child, of navigable:
+ for (auto const& child : navigable.children()) {
+ // 1. Recursively emit context created events given session and child.
+ recursively_emit_context_created_events(*child);
+ }
+ };
+
+ // 1. For each navigable in navigables:
+ // 1. Recursively emit context created events given session and navigable.
+ // NB: In the order of the top-level traversables.
+ for (auto& traversable : all_top_level_traversables()) {
+ if (top_level_traversable_ids.contains_slow(navigable_id(traversable)))
+ recursively_emit_context_created_events(traversable);
+ }
+
+ complete_command(command_id, JsonValue { move(events) });
+ return;
+ }
+
+ // https://w3c.github.io/webdriver-bidi/#event-script-realmCreated
+ if (event_name == "script.realmCreated"sv) {
+ // NB: The processes hosting the navigables' documents hold their realms. WebDriver gives the top-level
+ // traversables the subscription newly enables the event for, whether or not it is global.
+
+ Vector<CanonicalNavigable const*> navigables;
+ for (auto& traversable : all_top_level_traversables()) {
+ if (!top_level_traversable_ids.contains_slow(navigable_id(traversable)))
+ continue;
+ traversable.for_each_in_inclusive_subtree([&](CanonicalNavigable const& navigable) {
+ navigables.append(&navigable);
+ return IterationDecision::Continue;
+ });
+ }
+
+ struct State : RefCounted<State> {
+ Vector<Optional<JsonArray>> realms;
+ size_t remaining { 0 };
+ u64 command_id { 0 };
+ };
+ auto state = adopt_ref(*new State);
+ state->realms.resize(navigables.size());
+ state->remaining = navigables.size();
+ state->command_id = command_id;
+
+ auto finish = [this, state] {
+ JsonArray events;
+ for (auto& realms : state->realms) {
+ if (!realms.has_value())
+ continue;
+ for (auto& realm : realms->values()) {
+ JsonObject event;
+ event.set("method"sv, "script.realmCreated"sv);
+ event.set("params"sv, realm);
+ events.must_append(move(event));
+ }
+ }
+ complete_command(state->command_id, JsonValue { move(events) });
+ };
+
+ if (navigables.is_empty()) {
+ finish();
+ return;
+ }
+
+ for (size_t i = 0; i < navigables.size(); ++i) {
+ JsonObject params;
+ params.set("context"sv, navigable_id(*navigables[i]));
+ run_content_command(*navigables[i], "script.getRealms"_string, move(params), [state, i, finish](Web::WebDriver::Response response) {
+ if (!response.is_error() && response.value().is_object()) {
+ if (auto realms = response.value().as_object().get_array("realms"sv); realms.has_value())
+ state->realms[i] = *realms;
+ }
+ if (--state->remaining == 0)
+ finish();
+ });
+ }
+ return;
+ }
+
+ complete_command(command_id, JsonValue { JsonArray {} });
+}
+
+void WebDriverBiDi::run_content_command(CanonicalNavigable const& navigable, String const& method, JsonValue params, CommandResult on_complete)
+{
+ auto view = navigable.top_level_traversable().view();
+ if (!view.has_value()) {
+ on_complete(no_such_frame());
+ return;
+ }
+
+ auto command_id = m_next_content_command_id++;
+ m_pending_content_commands.set(command_id, move(on_complete));
+ view->run_webdriver_bidi_content_command(command_id, navigable.id(), method, move(params));
+}
+
+void WebDriverBiDi::run_command(u64 command_id, String const& method, JsonValue params_value)
+{
+ ensure_session_is_active();
+
+ // NB: A command may complete after the connection to WebDriver, and this object with it, went away.
+ auto on_complete = [command_id](Web::WebDriver::Response response) {
+ if (auto* webdriver_bidi = WebDriverBiDi::the())
+ webdriver_bidi->complete_command(command_id, move(response));
+ };
+
+ if (!params_value.is_object()) {
+ on_complete(invalid_argument("Command parameters must be an object"sv));
+ return;
+ }
+ auto const& params = params_value.as_object();
+
+ if (method == "browsingContext.activate"sv)
+ return browsing_context_activate(params, move(on_complete));
+ if (method == "browsingContext.close"sv)
+ return browsing_context_close(params, move(on_complete));
+ if (method == "browsingContext.create"sv)
+ return browsing_context_create(params, move(on_complete));
+ if (method == "browsingContext.getTree"sv)
+ return browsing_context_get_tree(params, move(on_complete));
+ if (method == "browsingContext.navigate"sv)
+ return browsing_context_navigate(params, move(on_complete));
+ if (method == "browsingContext.reload"sv)
+ return browsing_context_reload(params, move(on_complete));
+ if (method == "browsingContext.setViewport"sv)
+ return browsing_context_set_viewport(params, move(on_complete));
+ if (method == "browsingContext.traverseHistory"sv)
+ return browsing_context_traverse_history(params, move(on_complete));
+
+ if (method == "script.addPreloadScript"sv)
+ return script_add_preload_script(params, move(on_complete));
+ if (method == "script.removePreloadScript"sv)
+ return script_remove_preload_script(params, move(on_complete));
+ if (method == "script.getRealms"sv)
+ return script_get_realms(params, move(on_complete));
+ if (method.is_one_of("script.callFunction"sv, "script.disown"sv, "script.evaluate"sv))
+ return route_to_script_target(method, params, move(on_complete));
+
+ on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownCommand, "Command is not supported"sv));
+}
+
+// NB: Every top-level traversable that is not a tab created in the OS window of another one has an OS window of its
+// own, which is named by the traversable's id.
+String WebDriverBiDi::os_window_of(String const& top_level_traversable_id) const
+{
+ return m_tab_windows.get(top_level_traversable_id).value_or(top_level_traversable_id);
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-browsingContext-activate
+void WebDriverBiDi::browsing_context_activate(JsonObject const& params, CommandResult on_complete)
+{
+ // 1. Let navigable id be the value of the command parameters["context"] field.
+ auto navigable_id = TRY_OR_COMPLETE(get_string(params, "context"sv));
+
+ // 2. Let navigable be the result of trying to get a navigable with navigable id.
+ // 3. If navigable is not a top-level traversable, return error with error code invalid argument.
+ auto* traversable = TRY_OR_COMPLETE(get_a_top_level_traversable(navigable_id));
+
+ // 4. Return activate a navigable with navigable.
+ // https://w3c.github.io/webdriver-bidi/#activate-a-navigable
+ auto view = traversable->view();
+
+ // 1. Run implementation-specific steps so that navigable's system visibility state becomes visible. If this is not
+ // possible return error with error code unsupported operation.
+ // NB: The other tabs of its OS window become hidden.
+ auto os_window = os_window_of(navigable_id);
+ for (auto& other_traversable : all_top_level_traversables()) {
+ auto other_id = WebDriverBiDi::navigable_id(other_traversable);
+ if (&other_traversable == traversable || os_window_of(other_id) != os_window)
+ continue;
+ if (auto other_view = other_traversable.view(); other_view.has_value())
+ other_view->set_system_visibility_state(Web::HTML::VisibilityState::Hidden);
+ }
+ view->set_system_visibility_state(Web::HTML::VisibilityState::Visible);
+ if (view->on_activate_tab)
+ view->on_activate_tab();
+
+ // 2. Run implementation-specific steps to set the system focus on the navigable if it is not focused.
+ // NB: Other top-level traversables lose the system focus.
+ for (auto& other_traversable : all_top_level_traversables()) {
+ if (&other_traversable != traversable)
+ other_traversable.set_has_system_focus(false, nullptr);
+ }
+ traversable->set_has_system_focus(true, nullptr);
+
+ // 3. Return success with data null.
+ on_complete(JsonValue {});
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-browsingContext-close
+void WebDriverBiDi::browsing_context_close(JsonObject const& params, CommandResult on_complete)
+{
+ // 1. Let navigable id be the value of the context field of command parameters.
+ auto navigable_id = TRY_OR_COMPLETE(get_string(params, "context"sv));
+
+ // 2. Let prompt unload be the value of the promptUnload field of command parameters.
+ auto prompt_unload = TRY_OR_COMPLETE(get_optional_bool(params, "promptUnload"sv)).value_or(false);
+
+ // 3. Let navigable be the result of trying to get a navigable with navigable id.
+ // 4. Assert: navigable is not null.
+ // 5. If navigable is not a top-level traversable, return error with error code invalid argument.
+ auto* traversable = TRY_OR_COMPLETE(get_a_top_level_traversable(navigable_id));
+ auto view = traversable->view();
+
+ // 6. If prompt unload is true:
+ if (prompt_unload) {
+ // 1. Close navigable.
+ view->request_close();
+
+ // NB: A prompt to unload can keep the navigable open, so the command does not wait for it to close.
+ on_complete(JsonValue {});
+ return;
+ }
+
+ // 7. Otherwise:
+ // 1. Close navigable without prompting to unload.
+ // 8. Return success with data null.
+ // NB: The command completes once the navigable is closed.
+ m_pending_close_commands.ensure(view->handle()).append(move(on_complete));
+ view->prepare_for_close_without_prompting()();
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-browsingContext-create
+void WebDriverBiDi::browsing_context_create(JsonObject const& params, CommandResult on_complete)
+{
+ // 1. Let type be the value of the type field of command parameters.
+ auto type = TRY_OR_COMPLETE(get_string(params, "type"sv));
+ if (!type.is_one_of("tab"sv, "window"sv))
+ return on_complete(invalid_argument("Parameter 'type' must be \"tab\" or \"window\""sv));
+
+ // 2. Let reference navigable id be the value of the referenceContext field of command parameters, if present, or
+ // null otherwise.
+ auto reference_navigable_id = TRY_OR_COMPLETE(get_optional_string(params, "referenceContext"sv));
+
+ auto background = TRY_OR_COMPLETE(get_optional_bool(params, "background"sv)).value_or(false);
+
+ // 3. If reference navigable id is not null, let reference navigable be the result of trying to get a navigable with
+ // reference navigable id. Otherwise let reference navigable be null.
+ // 4. If reference navigable is not null and is not a top-level traversable, return error with error code invalid
+ // argument.
+ CanonicalTraversable* reference_navigable = nullptr;
+ if (reference_navigable_id.has_value())
+ reference_navigable = TRY_OR_COMPLETE(get_a_top_level_traversable(*reference_navigable_id));
+
+ // 5. If the implementation is unable to create a new top-level traversable for any reason then return error with
+ // error code unsupported operation.
+
+ // 6. Let user context be the default user context if reference navigable is null, and reference navigable'
+ // associated user context otherwise.
+ // 7. Let user context id be the value of the userContext field of command parameters if present, or null otherwise.
+ auto user_context_id = TRY_OR_COMPLETE(get_optional_string(params, "userContext"sv));
+
+ // 8. If user context id is not null, set user context to the result of trying to get user context with user
+ // context id.
+ // 9. If user context is null, return error with error code no such user context.
+ if (user_context_id.has_value() && *user_context_id != DEFAULT_USER_CONTEXT_ID)
+ return on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchUserContext, "User context not found"sv));
+
+ // 10. If the implementation is unable to create a new top-level traversable with associated user context user
+ // context for any reason, return error with error code unsupported operation.
+
+ // 11. Let traversable be the result of trying to create a new top-level traversable steps with null, empty string,
+ // null, and false, and setting the associated user context for the newly created top-level traversable to user
+ // context.
+ // NB: The process hosting the reference navigable's document, or any top-level traversable's, opens the new
+ // top-level traversable the way the browser opens a window for a page.
+ if (!reference_navigable) {
+ auto traversables = all_top_level_traversables();
+ if (traversables.is_empty())
+ return on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnsupportedOperation, "No browsing context to create a new one from"sv));
+ reference_navigable = &traversables.first();
+ }
+
+ JsonObject create_params;
+ create_params.set("type"sv, type);
+ auto reference_handle = navigable_id(*reference_navigable);
+
+ // NB: The process names the top-level traversable it created, which is not one of those that exist now.
+ HashTable<String> existing_handles;
+ for (auto& traversable : all_top_level_traversables())
+ existing_handles.set(navigable_id(traversable));
+
+ run_content_command(*reference_navigable, "browsingContext.create"_string, move(create_params), [this, background, is_tab = type == "tab"sv, reference_handle = move(reference_handle), existing_handles = move(existing_handles), on_complete = move(on_complete)](Web::WebDriver::Response response) mutable {
+ if (response.is_error())
+ return on_complete(move(response));
+
+ Optional<String> handle;
+ if (response.value().is_object()) {
+ if (auto context = response.value().as_object().get_string("context"sv); context.has_value())
+ handle = *context;
+ }
+ if (!handle.has_value() || existing_handles.contains(*handle) || get_a_top_level_traversable(*handle).is_error())
+ return on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Unable to create a top-level traversable"sv));
+
+ // NB: A tab shares the OS window of the reference navigable, which only shows its active tab.
+ if (is_tab)
+ m_tab_windows.set(*handle, os_window_of(reference_handle));
+
+ // NB: Opening the traversable activated it.
+ if (background) {
+ if (auto new_view = get_a_top_level_traversable(*handle).value()->view(); new_view.has_value()) {
+ new_view->traversable().set_has_system_focus(false, nullptr);
+ if (is_tab)
+ new_view->set_system_visibility_state(Web::HTML::VisibilityState::Hidden);
+ }
+ JsonObject reference_params;
+ reference_params.set("context"sv, reference_handle);
+ browsing_context_activate(reference_params, [](auto) { });
+ }
+
+ // 12. If the value of the command parameters' background field is false:
+ if (!background) {
+ // 1. Let activate result be the result of activate a navigable with the newly created navigable.
+ // 2. If activate result is an error, return activate result.
+ JsonObject activate_params;
+ activate_params.set("context"sv, *handle);
+ browsing_context_activate(activate_params, [](auto) { });
+ }
+
+ // 13. Let body be a map matching the browsingContext.CreateResult production, with the context field set to
+ // traversable's navigable id and the userContext property set to the user context id of traversable's
+ // associated user context.
+ JsonObject body;
+ body.set("context"sv, *handle);
+ body.set("userContext"sv, DEFAULT_USER_CONTEXT_ID);
+
+ // 14. Return success with data body.
+ on_complete(JsonValue { move(body) });
+ });
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-browsingContext-getTree
+void WebDriverBiDi::browsing_context_get_tree(JsonObject const& params, CommandResult on_complete)
+{
+ // 1. Let root id be the value of the root field of command parameters if present, or null otherwise.
+ auto root_id = TRY_OR_COMPLETE(get_optional_string(params, "root"sv));
+
+ // 2. Let max depth be the value of the maxDepth field of command parameters if present, or null otherwise.
+ Optional<u64> max_depth;
+ if (auto value = params.get("maxDepth"sv); value.has_value()) {
+ max_depth = as_js_uint(*value);
+ if (!max_depth.has_value())
+ return on_complete(invalid_argument("Parameter 'maxDepth' must be an unsigned integer"sv));
+ }
+
+ // 3. Let navigables be an empty list.
+ Vector<CanonicalNavigable const*> navigables;
+
+ // 4. If root id is not null, append the result of trying to get a navigable given root id to navigables. Otherwise
+ // append all top-level traversables to navigables.
+ if (root_id.has_value()) {
+ navigables.append(TRY_OR_COMPLETE(get_a_navigable(*root_id)));
+ } else {
+ for (auto& traversable : all_top_level_traversables())
+ navigables.append(&traversable);
+ }
+
+ // 5. Let navigables infos be an empty list.
+ JsonArray navigables_infos;
+
+ // 6. For each navigable of navigables:
+ for (auto const* navigable : navigables) {
+ // 1. Let info be the result of get the navigable info given navigable, max depth, and true.
+ // 2. Append info to navigables infos
+ navigables_infos.must_append(get_the_navigable_info(*navigable, max_depth, true));
+ }
+
+ // 7. Let body be a map matching the browsingContext.GetTreeResult production, with the contexts field set to
+ // navigables infos.
+ JsonObject body;
+ body.set("contexts"sv, move(navigables_infos));
+
+ // 8. Return success with data body.
+ on_complete(JsonValue { move(body) });
+}
+
+static ErrorOr<Optional<StringView>, Web::WebDriver::Error> get_wait_condition(JsonObject const& params)
+{
+ auto wait = TRY(get_optional_string(params, "wait"sv));
+ if (!wait.has_value())
+ return Optional<StringView> {};
+
+ // browsingContext.ReadinessState = "none" / "interactive" / "complete"
+ for (auto readiness_state : { "none"sv, "interactive"sv, "complete"sv }) {
+ if (*wait == readiness_state)
+ return readiness_state;
+ }
+ return invalid_argument("Parameter 'wait' must be a readiness state"sv);
+}
+
+// https://w3c.github.io/webdriver-bidi/#await-a-navigation
+void WebDriverBiDi::await_a_navigation(CanonicalNavigable& navigable, URL::URL url, WaitCondition wait_condition, CommandResult on_complete)
+{
+ // 1. Let navigation id be the string representation of a UUID based on truly random, or pseudo-random numbers.
+ // 2. Navigate navigable with resource request, and using navigable's active document as the source Document, with
+ // navigation id navigation id, and history handling behavior history handling. If ignore cache is true, the
+ // navigation must not load resources from the HTTP cache.
+ // NB: The browser's UI navigates the navigable, which generates the navigation id.
+ auto navigation = navigable.prepare_navigation(move(url));
+ auto navigation_id = navigation.navigation_id;
+ auto navigable_id = navigable.id();
+
+ // 3. Let (event received, navigation status) be await given «"navigation started", "navigation failed",
+ // "fragment navigated"», and navigation id.
+ await({ "navigation started"sv, "navigation failed"sv, "fragment navigated"sv }, navigable_id, navigation_id, [this, navigable_id, navigation_id, wait_condition, on_complete = move(on_complete)](StringView, NavigationStatus navigation_status) mutable {
+ // 4. Assert: navigation status's id is navigation id.
+ VERIFY(navigation_status.id == navigation_id);
+
+ // 5. If navigation status's status is "complete":
+ if (navigation_status.status == NavigationStatusType::Complete) {
+ // 1. Let body be a map matching the browsingContext.NavigateResult production, with the navigation field set
+ // to navigation id, and the url field set to the result of the URL serializer given navigation status's
+ // url.
+ JsonObject body;
+ body.set("navigation"sv, navigation_id.to_utf8());
+ body.set("url"sv, navigation_status.url.serialize());
+
+ // 2. Return success with data body.
+ on_complete(JsonValue { move(body) });
+ return;
+ }
+
+ // 6. If navigation status's status is "canceled" return error with error code unknown error.
+ if (navigation_status.status == NavigationStatusType::Canceled) {
+ on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Navigation was canceled"sv));
+ return;
+ }
+
+ // 7. Assert: navigation status's status is "pending" and navigation id is not null.
+ VERIFY(navigation_status.status == NavigationStatusType::Pending);
+
+ await_navigation_completion(navigable_id, navigation_id, wait_condition, move(on_complete));
+ });
+
+ if (navigable.is_top_level_traversable()) {
+ if (auto view = static_cast<CanonicalTraversable&>(navigable).view(); view.has_value()) {
+ view->load(move(navigation));
+ return;
+ }
+ }
+ navigable.begin_navigation(move(navigation));
+}
+
+void WebDriverBiDi::await_navigation_completion(Web::HTML::CrossProcessId navigable_id, Utf16String const& navigation_id, WaitCondition wait_condition, CommandResult on_complete)
+{
+ // 8. If wait condition is "committed", let event name be "committed".
+ // 9. Otherwise, if wait condition is "interactive", let event name be "domContentLoaded".
+ // 10. Otherwise, let event name be "load".
+ auto event_name = "load"sv;
+ if (wait_condition == WaitCondition::Committed)
+ event_name = "navigation committed"sv;
+ else if (wait_condition == WaitCondition::Interactive)
+ event_name = "domContentLoaded"sv;
+
+ // 11. Let (event received, status) be await given «event name, "download started", "navigation aborted",
+ // "navigation failed"» and navigation id.
+ await({ event_name, "download started"sv, "navigation aborted"sv, "navigation failed"sv }, navigable_id, navigation_id, [on_complete = move(on_complete)](StringView event_received, NavigationStatus status) {
+ // 12. If event received is "navigation failed" return error with error code unknown error.
+ if (event_received == "navigation failed"sv) {
+ on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Navigation failed"sv));
+ return;
+ }
+
+ // 13. Let body be a map matching the browsingContext.NavigateResult production, with the navigation field set to
+ // status's id, and the url field set to the result of the URL serializer given status's url.
+ JsonObject body;
+ if (status.id.has_value())
+ body.set("navigation"sv, status.id->to_utf8());
+ else
+ body.set("navigation"sv, JsonValue {});
+ body.set("url"sv, status.url.serialize());
+
+ // 14. Return success with data body.
+ on_complete(JsonValue { move(body) });
+ });
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-browsingContext-navigate
+void WebDriverBiDi::browsing_context_navigate(JsonObject const& params, CommandResult on_complete)
+{
+ // 1. Let navigable id be the value of the context field of command parameters.
+ auto navigable_id = TRY_OR_COMPLETE(get_string(params, "context"sv));
+ auto url = TRY_OR_COMPLETE(get_string(params, "url"sv));
+ auto wait = TRY_OR_COMPLETE(get_wait_condition(params));
+
+ // 2. Let navigable be the result of trying to get a navigable with navigable id.
+ // 3. Assert: navigable is not null.
+ auto* navigable = TRY_OR_COMPLETE(get_a_navigable(navigable_id));
+
+ // 4. Let wait condition be "committed".
+ auto wait_condition = WaitCondition::Committed;
+
+ // 5. If command parameters contains wait and command parameters[wait] is not "none", set wait condition to command
+ // parameters[wait].
+ if (wait == "interactive"sv)
+ wait_condition = WaitCondition::Interactive;
+ else if (wait == "complete"sv)
+ wait_condition = WaitCondition::Complete;
+
+ // 6. Let url be the value of the url field of command parameters.
+ // 7. Let document be navigable's active document.
+ // 8. Let base be document's base URL.
+ // FIXME: The browser process does not know a document's base URL, which a <base> element can change.
+ auto const& base = navigable->active_document_url();
+
+ // 9. Let url record be the result of applying the URL parser to url, with base URL base.
+ auto url_record = URL::Parser::basic_parse(url, base);
+
+ // 10. If url record is failure, return error with error code invalid argument.
+ if (!url_record.has_value())
+ return on_complete(invalid_argument("Parameter 'url' is not a valid URL"sv));
+
+ // 11. Let request be a new request whose URL is url record.
+ // 12. Return the result of await a navigation with navigable, request and wait condition.
+ await_a_navigation(*navigable, url_record.release_value(), wait_condition, move(on_complete));
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-browsingContext-reload
+void WebDriverBiDi::browsing_context_reload(JsonObject const& params, CommandResult on_complete)
+{
+ // 1. Let navigable id be the value of the context field of command parameters.
+ auto navigable_id = TRY_OR_COMPLETE(get_string(params, "context"sv));
+ auto ignore_cache_value = TRY_OR_COMPLETE(get_optional_bool(params, "ignoreCache"sv));
+ auto wait = TRY_OR_COMPLETE(get_wait_condition(params));
+
+ // 2. Let navigable be the result of trying to get a navigable with navigable id.
+ // 3. Assert: navigable is not null.
+ auto* navigable = TRY_OR_COMPLETE(get_a_navigable(navigable_id));
+
+ // 4. Let ignore cache be the the value of the ignoreCache field of command parameters if present, or false otherwise.
+ auto ignore_cache = ignore_cache_value.value_or(false);
+
+ // 5. Let wait condition be "committed".
+ auto wait_condition = WaitCondition::Committed;
+
+ // 6. If command parameters contains wait and command parameters[wait] is not "none", set wait condition to command
+ // parameters[wait].
+ if (wait == "interactive"sv)
+ wait_condition = WaitCondition::Interactive;
+ else if (wait == "complete"sv)
+ wait_condition = WaitCondition::Complete;
+
+ // 7. Let document be navigable's active document.
+ // 8. Let url be document's URL.
+ // 9. Let request be a new request whose URL is url.
+ // 10. Return the result of await a navigation with navigable, request, wait condition, history handling "reload",
+ // and ignore cache ignore cache.
+ // NB: The browser's UI reloads the navigable's active document by applying the reload history step, whose navigation
+ // id is passed through the history job to the replacement document.
+ // NB: A child navigable is navigated to the URL of its active document, which replaces its session history entry.
+ if (!navigable->is_top_level_traversable()) {
+ await_a_navigation(*navigable, navigable->active_document_url(), wait_condition, move(on_complete));
+ return;
+ }
+
+ auto& traversable = static_cast<CanonicalTraversable&>(*navigable);
+
+ // NB: A reload that another reload replaces is canceled.
+ if (auto previous_waiter = m_reload_waiters.take(traversable.id()); previous_waiter.has_value())
+ previous_waiter->on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Navigation was canceled"sv));
+ auto navigation_id = Utf16String::from_utf8(generate_random_uuid());
+ m_reload_waiters.set(traversable.id(), { navigation_id, wait_condition, move(on_complete) });
+ traversable.view()->reload_for_webdriver_bidi(ignore_cache ? BypassCache::Yes : BypassCache::No, move(navigation_id));
+}
+
+static constexpr double MAXIMUM_DEVICE_VIEWPORT_DIMENSION = 16384;
+
+static Gfx::IntSize device_viewport_size(ViewImplementation const& view)
+{
+ auto size = view.viewport_size();
+ return { size.width().value(), size.height().value() };
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-browsingContext-setViewport
+void WebDriverBiDi::browsing_context_set_viewport(JsonObject const& params, CommandResult on_complete)
+{
+ // browsingContext.SetViewportParameters = {
+ // ? context: browsingContext.BrowsingContext,
+ // ? viewport: browsingContext.Viewport / null,
+ // ? devicePixelRatio: (float .gt 0.0) / null,
+ // ? userContexts: [+browser.UserContext],
+ // }
+ // browsingContext.Viewport = {
+ // width: js-uint,
+ // height: js-uint,
+ // }
+ Optional<Optional<Gfx::IntSize>> viewport;
+ if (auto value = params.get("viewport"sv); value.has_value()) {
+ if (value->is_null()) {
+ viewport = Optional<Gfx::IntSize> {};
+ } else {
+ if (!value->is_object())
+ return on_complete(invalid_argument("Parameter 'viewport' must be a viewport or null"sv));
+ auto width = value->as_object().get("width"sv);
+ auto height = value->as_object().get("height"sv);
+ auto width_value = width.has_value() ? as_js_uint(*width) : Optional<u64> {};
+ auto height_value = height.has_value() ? as_js_uint(*height) : Optional<u64> {};
+ if (!width_value.has_value() || !height_value.has_value())
+ return on_complete(invalid_argument("The width and height of the viewport must be unsigned integers"sv));
+ if (*width_value > NumericLimits<i32>::max() || *height_value > NumericLimits<i32>::max())
+ return on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnsupportedOperation, "The viewport is too large"sv));
+ viewport = Gfx::IntSize { static_cast<int>(*width_value), static_cast<int>(*height_value) };
+ }
+ }
+
+ Optional<Optional<double>> device_pixel_ratio;
+ if (auto value = params.get("devicePixelRatio"sv); value.has_value()) {
+ if (value->is_null()) {
+ device_pixel_ratio = Optional<double> {};
+ } else {
+ auto number = value->get_number_with_precision_loss<double>();
+ if (!number.has_value() || !(*number > 0))
+ return on_complete(invalid_argument("Parameter 'devicePixelRatio' must be a number greater than 0"sv));
+ device_pixel_ratio = number;
+ }
+ }
+
+ auto context = TRY_OR_COMPLETE(get_optional_string(params, "context"sv));
+ auto user_contexts = TRY_OR_COMPLETE(get_optional_non_empty_list_of_strings(params, "userContexts"sv));
+
+ // 1. If the implementation is unable to adjust the layout viewport parameters with the given command parameters for
+ // any reason, return error with error code unsupported operation.
+
+ // 2. If command parameters contains "userContexts" and command parameters contains "context", return error with
+ // error code invalid argument.
+ if (context.has_value() && user_contexts.has_value())
+ return on_complete(invalid_argument("Parameters 'context' and 'userContexts' are mutually exclusive"sv));
+
+ // 3. Let navigables be a set.
+ Vector<CanonicalTraversable*> navigables;
+
+ // 4. If the context field of command parameters is present:
+ if (context.has_value()) {
+ // 1. Let navigable id be the value of the context field of command parameters.
+ // 2. Let navigable be the result of trying to get a navigable with navigable id.
+ // 3. If navigable is not a top-level traversable, return error with error code invalid argument.
+ // 4. Append navigable to navigables.
+ navigables.append(TRY_OR_COMPLETE(get_a_top_level_traversable(*context)));
+ }
+ // 5. Otherwise, if the userContexts field of command parameters is present:
+ else if (user_contexts.has_value()) {
+ // 1. Let user contexts be the result of trying to get valid user contexts with command
+ // parameters["userContexts"].
+ for (auto const& user_context_id : *user_contexts) {
+ if (user_context_id != DEFAULT_USER_CONTEXT_ID)
+ return on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchUserContext, "User context not found"sv));
+ }
+
+ // 2. For each user context of user contexts:
+ // 1. Set viewport overrides map[user context] to a struct.
+ // 2. If command parameters contains "viewport":
+ // 1. Set viewport overrides map[user context]'s viewport to command parameters["viewport"].
+ // 3. If command parameters contains "devicePixelRatio":
+ // 1. Set viewport overrides map[user context]'s devicePixelRatio to command parameters["devicePixelRatio"].
+ // 4. For each top-level traversable of the list of all top-level traversables whose associated user context
+ // is user context:
+ // 1. Append top-level traversable to navigables.
+ // FIXME: Apply the overrides of a user context to the top-level traversables created after this.
+ for (auto& traversable : all_top_level_traversables())
+ navigables.append(&traversable);
+ }
+ // 6. Otherwise, return error with error code invalid argument.
+ else {
+ return on_complete(invalid_argument("Either parameter 'context' or 'userContexts' must be given"sv));
+ }
+
+ struct ViewportChange {
+ WeakPtr<ViewImplementation> view;
+ String handle;
+ ViewportDefaults defaults;
+ double ratio;
+ Gfx::IntSize device_viewport;
+ Optional<Gfx::IntSize> css_override;
+ };
+ Vector<ViewportChange> changes;
+ for (auto* navigable : navigables) {
+ auto view = navigable->view();
+ if (!view.has_value())
+ continue;
+
+ // NB: The layout viewport of a top-level traversable is the viewport of its view, which a headless view takes
+ // the size of its window for. The view remembers the size it had before the first override, which is its
+ // implementation-defined default.
+ auto defaults = m_viewport_defaults.get(view->handle()).value_or(ViewportDefaults { .viewport_size = device_viewport_size(*view), .device_pixel_ratio = view->device_pixel_ratio() });
+
+ auto current_ratio = view->device_pixel_ratio();
+ Optional<Gfx::IntSize> css_override;
+ if (auto saved = m_css_viewport_overrides.get(view->handle()); saved.has_value() && saved->device_size == device_viewport_size(*view))
+ css_override = saved->css_size;
+ auto css_viewport = css_override.value_or(device_viewport_size(*view).to_type<double>().scaled(1.0 / current_ratio).to_type<int>());
+
+ // 8. If command parameters contains the devicePixelRatio field:
+ // 1. Let device pixel ratio be the command parameters["devicePixelRatio"].
+ // 2. For each navigable of navigables:
+ // 1. For the navigable and all descendant navigables:
+ // 1. Set device pixel ratio override with navigable and device pixel ratio.
+ auto ratio = current_ratio;
+ if (device_pixel_ratio.has_value())
+ ratio = device_pixel_ratio->value_or(defaults.device_pixel_ratio);
+
+ // 7. If command parameters contains the viewport field:
+ // 1. Let viewport be the command parameters["viewport"].
+ // 2. For each navigable of navigables:
+ // 1. Set viewport with navigable and viewport.
+ // 2. Run the resizing viewports steps with navigable's active document.
+ if (viewport.has_value()) {
+ css_override = *viewport;
+ css_viewport = viewport->value_or(defaults.viewport_size.to_type<double>().scaled(1.0 / defaults.device_pixel_ratio).to_type<int>());
+ }
+
+ // NB: This is step 1 for a viewport larger than the bitmaps that back the viewport of a view can be.
+ auto device_viewport = css_viewport.to_type<double>().scaled(ratio);
+ if (!(device_viewport.width() <= MAXIMUM_DEVICE_VIEWPORT_DIMENSION) || !(device_viewport.height() <= MAXIMUM_DEVICE_VIEWPORT_DIMENSION))
+ return on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnsupportedOperation, "The viewport is too large"sv));
+
+ // NB: Round up so conversion back to CSS pixels does not reduce the requested integer viewport.
+ Gfx::IntSize rounded_device_viewport { static_cast<int>(ceil(device_viewport.width())), static_cast<int>(ceil(device_viewport.height())) };
+ changes.append({ view->make_weak_ptr(), view->handle(), defaults, ratio, rounded_device_viewport, css_override });
+ }
+
+ // NB: A failed command must leave both the views and their remembered defaults unchanged. Cache all defaults
+ // before calling resize callbacks, which may destroy another view or reenter viewport handling.
+ for (auto const& change : changes) {
+ if (change.view) {
+ m_viewport_defaults.ensure(change.handle, [&] { return change.defaults; });
+ if (change.css_override.has_value())
+ m_css_viewport_overrides.set(change.handle, { *change.css_override, change.device_viewport });
+ else
+ m_css_viewport_overrides.remove(change.handle);
+ }
+ }
+ for (auto const& change : changes) {
+ auto* view = change.view.ptr();
+ if (!view)
+ continue;
+ if (change.ratio != view->device_pixel_ratio())
+ view->set_device_pixel_ratio_for_testing(view->page(), change.ratio);
+ if (view->on_resize_window)
+ view->on_resize_window(change.device_viewport);
+ }
+
+ // 9. Return success with data null.
+ on_complete(JsonValue {});
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-browsingContext-traverseHistory
+void WebDriverBiDi::browsing_context_traverse_history(JsonObject const& params, CommandResult on_complete)
+{
+ auto navigable_id = TRY_OR_COMPLETE(get_string(params, "context"sv));
+
+ // browsingContext.TraverseHistoryParameters = {
+ // context: browsingContext.BrowsingContext,
+ // delta: js-int,
+ // }
+ // js-int = -9007199254740991..9007199254740991
+ auto delta_value = params.get("delta"sv);
+ auto delta = delta_value.has_value() ? delta_value->get_number_with_precision_loss<double>() : Optional<double> {};
+ if (!delta.has_value() || trunc(*delta) != *delta || fabs(*delta) > 9007199254740991.0)
+ return on_complete(invalid_argument("Parameter 'delta' must be an integer"sv));
+
+ // 1. Let navigable be the result of trying to get a navigable with command parameters["context"].
+ // 2. If navigable is not a top-level traversable, return error with error code invalid argument.
+ // 3. Assert: navigable is not null.
+ auto* traversable = TRY_OR_COMPLETE(get_a_top_level_traversable(navigable_id));
+
+ // 4. Let delta be command parameters["delta"].
+ // 5. Let resume id be a unique string.
+ // 6. Queue a task on navigable's session history traversal queue to run the following steps:
+ // 1. Let all steps be the result of getting all used history steps for navigable.
+ // 2. Let current index be the index of navigable's current session history step within all steps.
+ // 3. Let target index be current index plus delta.
+ // 4. Let valid entry be false if all steps[target index] does not exist, or true otherwise.
+ // 5. Resume with "check history", resume id, and valid entry.
+ // 7. Let is valid entry be await with «"check history"», and resume id.
+ // NB: The browser process holds the session history, so it checks the entry right away.
+ auto all_steps = traversable->session_history().used_steps();
+ auto current_index = all_steps.find_first_index(traversable->session_history().current_step());
+ auto target_index = current_index.has_value() ? static_cast<double>(*current_index) + *delta : -1.0;
+ auto is_valid_entry = target_index >= 0 && target_index < static_cast<double>(all_steps.size());
+
+ // 8. If is valid entry is false, return error with error code no such history entry.
+ if (!is_valid_entry)
+ return on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchHistoryEntry, "No history entry at the given delta"sv));
+
+ // 9. Traverse the history by a delta given delta and navigable.
+ // 10. TODO: Support waiting for the history traversal to complete.
+ // 11. Let body be a map matching the browsingContext.TraverseHistoryResult production.
+ // 12. Return success with data body.
+ // NB: The command completes once the traversal is applied.
+ // NB: A traversal that is canceled or that does not apply completes the command with an error.
+ struct PendingTraversal : RefCounted<PendingTraversal> {
+ explicit PendingTraversal(CommandResult on_complete)
+ : on_complete(move(on_complete))
+ {
+ }
+ ~PendingTraversal()
+ {
+ if (on_complete)
+ on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "History traversal did not complete"sv));
+ }
+ CommandResult on_complete;
+ };
+ auto pending_traversal = adopt_ref(*new PendingTraversal(move(on_complete)));
+ traversable->view()->traverse_the_history_by_delta(static_cast<int>(*delta), CheckForCancelation::Yes, [pending_traversal] {
+ if (auto on_complete = move(pending_traversal->on_complete))
+ on_complete(JsonValue {});
+ });
+}
+
+// https://w3c.github.io/webdriver-bidi/#realm-id
+// NB: The id of a realm names the document whose relevant realm it is, which the process hosting it gave.
+static Optional<Web::HTML::CrossProcessId> document_id_of_realm_id(StringView realm_id)
+{
+ auto parts = realm_id.split_view('.');
+ if (parts.size() != 2)
+ return {};
+
+ auto namespace_id = parts[0].to_number<u64>();
+ auto local_id = parts[1].to_number<u64>();
+ if (!namespace_id.has_value() || !local_id.has_value())
+ return {};
+
+ return Web::HTML::CrossProcessId { .namespace_id = *namespace_id, .local_id = *local_id };
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-a-realm
+static ErrorOr<CanonicalNavigable*, Web::WebDriver::Error> get_the_navigable_of_a_realm(StringView realm_id)
+{
+ // 1. If realm id is null, return success with data null.
+ // 2. If there is no realm with id realm id return error with error code no such frame
+ auto document_id = document_id_of_realm_id(realm_id);
+ if (!document_id.has_value())
+ return no_such_frame();
+
+ CanonicalNavigable* result = nullptr;
+ for (auto& traversable : all_top_level_traversables()) {
+ traversable.for_each_in_inclusive_subtree([&](CanonicalNavigable& navigable) {
+ if (navigable.active_document().id() != *document_id)
+ return IterationDecision::Continue;
+ result = &navigable;
+ return IterationDecision::Break;
+ });
+ if (result)
+ break;
+ }
+
+ if (!result)
+ return no_such_frame();
+
+ // 3. Let realm be the realm with id realm id.
+ // 4. Return success with data realm
+ return result;
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-a-realm-from-a-target
+void WebDriverBiDi::route_to_script_target(String const& method, JsonObject const& params, CommandResult on_complete)
+{
+ auto target = params.get("target"sv);
+ if (!target.has_value() || !target->is_object())
+ return on_complete(invalid_argument("Parameter 'target' must be an object"sv));
+
+ // 1. If target matches the script.ContextTarget production:
+ if (target->as_object().has("context"sv)) {
+ // 1. Let sandbox be null.
+ // 2. If target contains "sandbox", set sandbox to target["sandbox"].
+ // 3. Let realm be get a realm from a navigable with target["context"] and sandbox.
+ // https://w3c.github.io/webdriver-bidi/#get-a-realm-from-a-navigable
+ // 1. Let navigable be the result of trying to get a navigable with navigable id.
+ // NB: The process hosting the navigable's active document gets its realm.
+ auto navigable_id = TRY_OR_COMPLETE(get_string(target->as_object(), "context"sv));
+ auto* navigable = TRY_OR_COMPLETE(get_a_navigable(navigable_id));
+ run_content_command(*navigable, method, params, move(on_complete));
+ return;
+ }
+
+ // 2. Otherwise:
+ if (target->as_object().has("realm"sv)) {
+ // 1. Assert: target matches the script.RealmTarget production.
+ // 2. Let realm id be the value of the realm field of target.
+ auto realm_id = TRY_OR_COMPLETE(get_string(target->as_object(), "realm"sv));
+
+ // 3. Let realm be get a realm given realm id.
+ // NB: The process hosting the realm's document gets it.
+ auto* navigable = TRY_OR_COMPLETE(get_the_navigable_of_a_realm(realm_id));
+ run_content_command(*navigable, method, params, move(on_complete));
+ return;
+ }
+
+ on_complete(invalid_argument("Parameter 'target' must be a context or realm target"sv));
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-script-getRealms
+void WebDriverBiDi::script_get_realms(JsonObject const& params, CommandResult on_complete)
+{
+ auto context = TRY_OR_COMPLETE(get_optional_string(params, "context"sv));
+ auto type = TRY_OR_COMPLETE(get_optional_string(params, "type"sv));
+
+ // script.RealmType = "window" / "dedicated-worker" / "shared-worker" / "service-worker" / "worker" /
+ // "paint-worklet" / "audio-worklet" / "worklet"
+ if (type.has_value() && !type->is_one_of("window"sv, "dedicated-worker"sv, "shared-worker"sv, "service-worker"sv, "worker"sv, "paint-worklet"sv, "audio-worklet"sv, "worklet"sv))
+ return on_complete(invalid_argument("Parameter 'type' must be a realm type"sv));
+
+ // 1. Let environment settings be a list of all the environment settings objects that have their execution ready
+ // flag set.
+ // 2. If command parameters contains context:
+ // 1. Let navigable be the result of trying to get a navigable with command parameters["context"].
+ // NB: The processes hosting the navigables' documents hold their realms.
+ Vector<CanonicalNavigable const*> navigables;
+ if (context.has_value()) {
+ navigables.append(TRY_OR_COMPLETE(get_a_navigable(*context)));
+ } else {
+ for (auto& traversable : all_top_level_traversables()) {
+ traversable.for_each_in_inclusive_subtree([&](CanonicalNavigable const& navigable) {
+ navigables.append(&navigable);
+ return IterationDecision::Continue;
+ });
+ }
+ }
+
+ struct State : RefCounted<State> {
+ Vector<Optional<JsonArray>> realms;
+ size_t remaining { 0 };
+ CommandResult on_complete;
+ };
+ auto state = adopt_ref(*new State);
+ state->realms.resize(navigables.size());
+ state->remaining = navigables.size();
+ state->on_complete = move(on_complete);
+
+ auto finish = [state] {
+ // 3. Let realms be a list.
+ JsonArray realms;
+ for (auto& navigable_realms : state->realms) {
+ if (!navigable_realms.has_value())
+ continue;
+ for (auto& realm : navigable_realms->values())
+ realms.must_append(realm);
+ }
+
+ // 5. Let body be a map matching the script.GetRealmsResult production, with the realms field set to realms.
+ JsonObject body;
+ body.set("realms"sv, move(realms));
+
+ // 6. Return success with data body.
+ state->on_complete(JsonValue { move(body) });
+ };
+
+ if (navigables.is_empty()) {
+ finish();
+ return;
+ }
+
+ for (size_t i = 0; i < navigables.size(); ++i) {
+ JsonObject navigable_params;
+ navigable_params.set("context"sv, navigable_id(*navigables[i]));
+ if (type.has_value())
+ navigable_params.set("type"sv, *type);
+
+ run_content_command(*navigables[i], "script.getRealms"_string, move(navigable_params), [state, i, finish, single_navigable = context.has_value()](Web::WebDriver::Response response) {
+ if (response.is_error()) {
+ // NB: A navigable that went away while we asked has no realms to report.
+ if (single_navigable) {
+ state->on_complete(move(response));
+ return;
+ }
+ } else if (response.value().is_object()) {
+ if (auto realms = response.value().as_object().get_array("realms"sv); realms.has_value())
+ state->realms[i] = *realms;
+ }
+ if (--state->remaining == 0)
+ finish();
+ });
+ }
+}
+
+// https://w3c.github.io/webdriver-bidi/#type-script-ChannelValue
+static bool is_channel_value(JsonValue const& value)
+{
+ // script.ChannelValue = {
+ // type: "channel",
+ // value: script.ChannelProperties,
+ // }
+ // script.ChannelProperties = {
+ // channel: script.Channel,
+ // ? serializationOptions: script.SerializationOptions,
+ // ? ownership: script.ResultOwnership,
+ // }
+ if (!value.is_object())
+ return false;
+ auto const& object = value.as_object();
+ if (object.get_string("type"sv) != "channel"sv)
+ return false;
+ auto properties = object.get_object("value"sv);
+ if (!properties.has_value() || !properties->get_string("channel"sv).has_value())
+ return false;
+ if (auto ownership = properties->get("ownership"sv); ownership.has_value() && (!ownership->is_string() || !ownership->as_string().is_one_of("root"sv, "none"sv)))
+ return false;
+ if (auto options = properties->get("serializationOptions"sv); options.has_value() && Web::WebDriver::parse_serialization_options(*options).is_error())
+ return false;
+ return true;
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-script-addPreloadScript
+void WebDriverBiDi::script_add_preload_script(JsonObject const& params, CommandResult on_complete)
+{
+ // 1. If command parameters contains "userContexts" and command parameters contains "contexts", return error with
+ // error code invalid argument.
+ if (params.has("userContexts"sv) && params.has("contexts"sv))
+ return on_complete(invalid_argument("Parameters 'contexts' and 'userContexts' are mutually exclusive"sv));
+
+ // 2. Let function declaration be the functionDeclaration field of command parameters.
+ auto function_declaration = TRY_OR_COMPLETE(get_string(params, "functionDeclaration"sv));
+
+ // 3. Let arguments be the arguments field of command parameters if present, or an empty list otherwise.
+ JsonArray arguments;
+ if (auto value = params.get("arguments"sv); value.has_value()) {
+ if (!value->is_array())
+ return on_complete(invalid_argument("Parameter 'arguments' must be a list of channel values"sv));
+ for (auto const& argument : value->as_array().values()) {
+ if (!is_channel_value(argument))
+ return on_complete(invalid_argument("Parameter 'arguments' must be a list of channel values"sv));
+ arguments.must_append(argument);
+ }
+ }
+
+ auto contexts = TRY_OR_COMPLETE(get_optional_non_empty_list_of_strings(params, "contexts"sv));
+ auto input_user_contexts = TRY_OR_COMPLETE(get_optional_non_empty_list_of_strings(params, "userContexts"sv));
+ auto sandbox = TRY_OR_COMPLETE(get_optional_string(params, "sandbox"sv));
+
+ // 4. Let user contexts to be a set.
+ Vector<String> user_contexts;
+
+ // 5. Let navigables be null.
+ Optional<Vector<String>> navigables;
+
+ // 6. If the contexts field of command parameters is present:
+ if (contexts.has_value()) {
+ // 1. Set navigables to an empty set.
+ navigables = Vector<String> {};
+
+ // 2. For each navigable id of command parameters["contexts"]
+ for (auto const& navigable_id : *contexts) {
+ // 1. Let navigable be the result of trying to get a navigable with navigable id.
+ // 2. If navigable is not a top-level traversable, return error with error code invalid argument.
+ auto* traversable = TRY_OR_COMPLETE(get_a_top_level_traversable(navigable_id));
+
+ // 3. Append navigable to navigables.
+ if (!navigables->contains_slow(navigable_id))
+ navigables->append(navigable_id);
+
+ // NB: A process that hosts a frame of the traversable, and not the traversable itself, names it by its id.
+ auto traversable_id = MUST(String::formatted("{}-{}", traversable->id().namespace_id, traversable->id().local_id));
+ if (!navigables->contains_slow(traversable_id))
+ navigables->append(move(traversable_id));
+ }
+ }
+ // 7. Otherwise, if command parameters contains userContexts:
+ else if (input_user_contexts.has_value()) {
+ // 1. Set user contexts to create a set with command parameters["userContexts"].
+ for (auto const& user_context_id : *input_user_contexts) {
+ if (!user_contexts.contains_slow(user_context_id))
+ user_contexts.append(user_context_id);
+ }
+
+ // 2. For each user context id of user contexts:
+ for (auto const& user_context_id : user_contexts) {
+ // 1. Set user context to get user context with user context id.
+ // 2. If user context is null, return error with error code no such user context.
+ if (user_context_id != DEFAULT_USER_CONTEXT_ID)
+ return on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchUserContext, "User context not found"sv));
+ }
+ }
+
+ // 8. Let sandbox be the value of the "sandbox" field in command parameters, if present, or null otherwise.
+
+ // 9. Let script be the string representation of a UUID.
+ auto script = generate_random_uuid();
+
+ // 10. Let preload script map be session's preload script map.
+ // 11. Set preload script map[script] to a struct with function declaration function declaration, arguments
+ // arguments, contexts navigables, sandbox sandbox, and user contexts user contexts.
+ m_session_state.preload_scripts.append({
+ .id = script,
+ .function_declaration = move(function_declaration),
+ .arguments = move(arguments),
+ .contexts = move(navigables),
+ .sandbox = move(sandbox),
+ .user_contexts = move(user_contexts),
+ });
+ push_session_state();
+
+ // 12. Return a new map matching the script.AddPreloadScriptResult with the script field set to script.
+ JsonObject result;
+ result.set("script"sv, move(script));
+ on_complete(JsonValue { move(result) });
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-script-removePreloadScript
+void WebDriverBiDi::script_remove_preload_script(JsonObject const& params, CommandResult on_complete)
+{
+ // 1. Let script be the value of the "script" field in command parameters.
+ auto script = TRY_OR_COMPLETE(get_string(params, "script"sv));
+
+ // 2. Let preload script map be session's preload script map.
+ // 3. If preload script map does not contain script, return error with error code no such script.
+ // 4. Remove script from preload script map.
+ auto removed = m_session_state.preload_scripts.remove_first_matching([&](auto const& preload_script) {
+ return preload_script.id == script;
+ });
+ if (!removed)
+ return on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchScript, "Preload script not found"sv));
+
+ push_session_state();
+
+ // 5. Return null
+ on_complete(JsonValue {});
+}
+
+}
diff --git a/Libraries/LibWebView/WebDriverBiDi.h b/Libraries/LibWebView/WebDriverBiDi.h
new file mode 100644
index 00000000000..b9385663fa2
--- /dev/null
+++ b/Libraries/LibWebView/WebDriverBiDi.h
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Function.h>
+#include <AK/HashMap.h>
+#include <AK/HashTable.h>
+#include <AK/JsonObject.h>
+#include <AK/JsonValue.h>
+#include <AK/String.h>
+#include <AK/Utf16String.h>
+#include <AK/Vector.h>
+#include <LibGfx/Size.h>
+#include <LibURL/URL.h>
+#include <LibWebCommon/HTML/CrossProcessId.h>
+#include <LibWebCommon/WebDriver/BiDi.h>
+#include <LibWebCommon/WebDriver/Response.h>
+#include <LibWebView/Forward.h>
+
+namespace WebView {
+
+class WebDriverBrowserConnection;
+
+// https://w3c.github.io/webdriver-bidi/
+// NB: The browser process runs the commands of a BiDi session that involve navigables, and routes those that run in the
+// process hosting a navigable's document to it. It exists only while WebDriver drives the browser.
+class WebDriverBiDi {
+ AK_MAKE_NONCOPYABLE(WebDriverBiDi);
+ AK_ALLOC_WITH_KMALLOC;
+ AK_MAKE_NONMOVABLE(WebDriverBiDi);
+
+public:
+ static WebDriverBiDi* the() { return s_the; }
+
+ explicit WebDriverBiDi(WebDriverBrowserConnection&);
+ ~WebDriverBiDi();
+
+ void run_command(u64 command_id, String const& method, JsonValue params);
+ void get_top_level_traversables(u64 command_id, Vector<String> const& navigable_ids);
+ void run_subscribe_steps(u64 command_id, String const& event_name, Vector<String> const& top_level_traversable_ids);
+ void set_enabled_events(Vector<String> const& event_names);
+
+ bool is_event_enabled(StringView event_name) const { return m_enabled_events.contains(event_name); }
+ Web::WebDriver::BiDiSessionState const& session_state() const { return m_session_state; }
+
+ // Completes a command that a process hosting a navigable ran, if this object sent it.
+ bool did_complete_content_command(u64 command_id, Web::WebDriver::Response&);
+
+ // https://w3c.github.io/webdriver-bidi/#navigable-id
+ static String navigable_id(CanonicalNavigable const&);
+
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigable-created
+ void navigable_created(CanonicalNavigable const&, Optional<CanonicalNavigable const&> opener_navigable = {});
+ void top_level_traversable_did_get_window_handle(CanonicalTraversable const&);
+
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigable-destroyed
+ void navigable_destroyed(CanonicalNavigable const&);
+ void top_level_traversable_is_closing(CanonicalNavigable const&);
+ void top_level_traversable_did_close(String const& window_handle);
+
+ // NB: The navigations of a top-level traversable whose process crashed do not go on.
+ void top_level_traversable_did_crash(CanonicalTraversable const&);
+
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigation-status
+ enum class NavigationStatusType : u8 {
+ Canceled,
+ Pending,
+ Complete,
+ };
+ struct NavigationStatus {
+ Optional<Utf16String> id;
+ NavigationStatusType status { NavigationStatusType::Pending };
+ URL::URL url;
+ };
+
+ // NB: A reload canceled before its history step applies emits no navigation event.
+ void reload_did_not_apply(CanonicalTraversable const&, Optional<Utf16String> const& navigation_id);
+ void navigation_superseded_reload(CanonicalNavigable const&);
+
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigation-started
+ void navigation_started(CanonicalNavigable const&, NavigationStatus const&);
+
+ // https://w3c.github.io/webdriver-bidi/#webdriver-bidi-navigation-failed
+ void navigation_failed(CanonicalNavigable const&, NavigationStatus const&);
+
+ void did_receive_navigation_event(WebContentPage&, Web::HTML::CrossProcessId navigable_id, String const& name, Optional<Utf16String> navigation_id, URL::URL url);
+ void did_receive_event(WebContentPage&, Web::HTML::CrossProcessId navigable_id, String const& name, JsonValue params);
+
+private:
+ static WebDriverBiDi* s_the;
+
+ using CommandResult = Function<void(Web::WebDriver::Response)>;
+
+ void complete_command(u64 command_id, Web::WebDriver::Response);
+
+ void emit_event(StringView name, JsonValue params, Vector<String> top_level_traversable_ids);
+ void emit_event_for_navigable(StringView name, JsonValue params, CanonicalNavigable const&);
+
+ void ensure_session_is_active();
+ void push_session_state();
+
+ void run_content_command(CanonicalNavigable const&, String const& method, JsonValue params, CommandResult);
+
+ // https://w3c.github.io/webdriver-bidi/#get-the-navigable-info
+ JsonObject get_the_navigable_info(CanonicalNavigable const&, Optional<u64> max_depth, bool include_parent_id) const;
+
+ // https://w3c.github.io/webdriver-bidi/#get-the-navigation-info
+ JsonObject get_the_navigation_info(CanonicalNavigable const&, NavigationStatus const&) const;
+
+ // https://w3c.github.io/webdriver-bidi/#await
+ using ResumeSteps = Function<void(StringView event_name, NavigationStatus)>;
+ // NB: A navigation is awaited for the navigable it navigates, whose events alone resume it.
+ void await(Vector<StringView> events, Web::HTML::CrossProcessId navigable_id, Utf16String const& resume_id, ResumeSteps);
+
+ // https://w3c.github.io/webdriver-bidi/#resume
+ void resume(StringView name, Web::HTML::CrossProcessId navigable_id, Utf16String const& id, NavigationStatus const&);
+
+ // NB: The navigations awaited for a navigable that is gone, or whose process is gone, fail.
+ void fail_navigations_of(Function<bool(Web::HTML::CrossProcessId)> const& is_affected_navigable);
+ void remove_state_of_removed_navigables();
+
+ // https://w3c.github.io/webdriver-bidi/#await-a-navigation
+ enum class WaitCondition : u8 {
+ Committed,
+ Interactive,
+ Complete,
+ };
+ void await_a_navigation(CanonicalNavigable&, URL::URL, WaitCondition, CommandResult);
+ void await_navigation_completion(Web::HTML::CrossProcessId navigable_id, Utf16String const& navigation_id, WaitCondition, CommandResult);
+
+ void browsing_context_activate(JsonObject const& params, CommandResult);
+ void browsing_context_close(JsonObject const& params, CommandResult);
+ void browsing_context_create(JsonObject const& params, CommandResult);
+ void browsing_context_get_tree(JsonObject const& params, CommandResult);
+ void browsing_context_navigate(JsonObject const& params, CommandResult);
+ void browsing_context_reload(JsonObject const& params, CommandResult);
+ void browsing_context_set_viewport(JsonObject const& params, CommandResult);
+ void browsing_context_traverse_history(JsonObject const& params, CommandResult);
+ String os_window_of(String const& top_level_traversable_id) const;
+
+ void script_add_preload_script(JsonObject const& params, CommandResult);
+ void script_remove_preload_script(JsonObject const& params, CommandResult);
+ void script_get_realms(JsonObject const& params, CommandResult);
+ void route_to_script_target(String const& method, JsonObject const& params, CommandResult);
+
+ WebDriverBrowserConnection& m_connection;
+
+ HashTable<String> m_enabled_events;
+ Web::WebDriver::BiDiSessionState m_session_state;
+
+ u64 m_next_content_command_id;
+ HashMap<u64, CommandResult> m_pending_content_commands;
+
+ // https://w3c.github.io/webdriver-bidi/#wait-queue
+ struct Waiter {
+ Vector<StringView> events;
+ Web::HTML::CrossProcessId navigable_id;
+ ResumeSteps algorithm;
+ };
+ HashMap<Utf16String, Waiter> m_wait_queue;
+
+ // https://w3c.github.io/webdriver-bidi/#original-opener
+ HashMap<Web::HTML::CrossProcessId, String> m_original_openers;
+
+ // NB: The navigables whose destruction was reported before they were removed.
+ HashTable<Web::HTML::CrossProcessId> m_destroyed_navigables;
+
+ // NB: The info of each closing top-level traversable, taken before its navigables go away with it.
+ HashMap<Web::HTML::CrossProcessId, JsonObject> m_closing_traversable_infos;
+
+ // NB: The commands closing a top-level traversable complete once it is closed.
+ HashMap<String, Vector<CommandResult>> m_pending_close_commands;
+
+ // NB: Reload commands wait for events from their own navigation.
+ struct ReloadWaiter {
+ Utf16String navigation_id;
+ WaitCondition wait_condition;
+ CommandResult on_complete;
+ };
+ HashMap<Web::HTML::CrossProcessId, ReloadWaiter> m_reload_waiters;
+
+ // NB: The viewport a top-level traversable had before WebDriver BiDi first overrode it.
+ struct ViewportDefaults {
+ Gfx::IntSize viewport_size;
+ double device_pixel_ratio { 1.0 };
+ };
+ HashMap<String, ViewportDefaults> m_viewport_defaults;
+ struct ViewportOverride {
+ Gfx::IntSize css_size;
+ Gfx::IntSize device_size;
+ };
+ HashMap<String, ViewportOverride> m_css_viewport_overrides;
+
+ // NB: The OS window of each tab created in the OS window of another top-level traversable.
+ HashMap<String, String> m_tab_windows;
+};
+
+}
diff --git a/Libraries/LibWebView/WebDriverBrowserConnection.cpp b/Libraries/LibWebView/WebDriverBrowserConnection.cpp
index 8d1a6a495a6..0de514cd661 100644
--- a/Libraries/LibWebView/WebDriverBrowserConnection.cpp
+++ b/Libraries/LibWebView/WebDriverBrowserConnection.cpp
@@ -31,6 +31,7 @@ ErrorOr<NonnullRefPtr<WebDriverBrowserConnection>> WebDriverBrowserConnection::c
WebDriverBrowserConnection::WebDriverBrowserConnection(NonnullOwnPtr<IPC::Transport> transport)
: IPC::ConnectionToServer<WebDriverBrowserClientEndpoint, WebDriverBrowserServerEndpoint>(*this, move(transport))
+ , m_webdriver_bidi(make<WebDriverBiDi>(*this))
{
}
@@ -309,4 +310,24 @@ void WebDriverBrowserConnection::get_session_history(u64 command_id, String wind
async_command_complete(command_id, JsonValue { move(result) });
}
+void WebDriverBrowserConnection::bidi_command(u64 command_id, String method, JsonValue params)
+{
+ m_webdriver_bidi->run_command(command_id, method, move(params));
+}
+
+void WebDriverBrowserConnection::bidi_get_top_level_traversables(u64 command_id, Vector<String> navigable_ids)
+{
+ m_webdriver_bidi->get_top_level_traversables(command_id, navigable_ids);
+}
+
+void WebDriverBrowserConnection::bidi_run_subscribe_steps(u64 command_id, String event_name, Vector<String> top_level_traversable_ids)
+{
+ m_webdriver_bidi->run_subscribe_steps(command_id, event_name, top_level_traversable_ids);
+}
+
+void WebDriverBrowserConnection::set_bidi_enabled_events(Vector<String> event_names)
+{
+ m_webdriver_bidi->set_enabled_events(event_names);
+}
+
}
diff --git a/Libraries/LibWebView/WebDriverBrowserConnection.h b/Libraries/LibWebView/WebDriverBrowserConnection.h
index 37208dc9aa3..65ebbee45e5 100644
--- a/Libraries/LibWebView/WebDriverBrowserConnection.h
+++ b/Libraries/LibWebView/WebDriverBrowserConnection.h
@@ -9,6 +9,7 @@
#include <AK/Error.h>
#include <LibIPC/ConnectionToServer.h>
#include <LibIPC/Transport.h>
+#include <LibWebView/WebDriverBiDi.h>
#include <WebDriver/WebDriverBrowserClientEndpoint.h>
#include <WebDriver/WebDriverBrowserServerEndpoint.h>
@@ -40,6 +41,13 @@ private:
virtual void set_page_load_strategy(Web::WebDriver::PageLoadStrategy page_load_strategy) override;
virtual void set_strict_file_interactability(bool strict_file_interactability) override;
virtual void set_timeouts_configuration(JsonValue timeouts) override;
+
+ virtual void bidi_command(u64 command_id, String method, JsonValue params) override;
+ virtual void bidi_get_top_level_traversables(u64 command_id, Vector<String> navigable_ids) override;
+ virtual void bidi_run_subscribe_steps(u64 command_id, String event_name, Vector<String> top_level_traversable_ids) override;
+ virtual void set_bidi_enabled_events(Vector<String> event_names) override;
+
+ NonnullOwnPtr<WebDriverBiDi> m_webdriver_bidi;
};
}
diff --git a/Services/WebContent/CMakeLists.txt b/Services/WebContent/CMakeLists.txt
index 024122ddac7..d8980a57962 100644
--- a/Services/WebContent/CMakeLists.txt
+++ b/Services/WebContent/CMakeLists.txt
@@ -9,6 +9,7 @@ set(SOURCES
TestConnection.cpp
WebContentCompositorHost.cpp
WebContentConsoleClient.cpp
+ WebDriverBiDi.cpp
WebDriverConnection.cpp
WebUIConnection.cpp
)
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index 0e998a7a076..2c53d21ca77 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -108,6 +108,7 @@
#include <WebContent/TestConnection.h>
#include <WebContent/WebContentClientEndpoint.h>
#include <WebContent/WebContentCompositorHost.h>
+#include <WebContent/WebDriverBiDi.h>
namespace WebContent {
@@ -398,6 +399,23 @@ void ConnectionFromClient::run_webdriver_command(Web::PageId page_id, u64 comman
page->run_webdriver_command(command_id, navigable_id, name, move(payload), move(arguments));
}
+void ConnectionFromClient::run_webdriver_bidi_command(Web::PageId page_id, u64 command_id, Web::HTML::CrossProcessId navigable_id, String method, JsonValue params)
+{
+ auto page = this->page(page_id);
+ if (!page.has_value()) {
+ // NB: A command the driver is waiting on must be answered even when its page is gone here.
+ async_webdriver_command_complete(page_id, command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, "Browsing context not found"sv));
+ return;
+ }
+
+ WebContent::run_webdriver_bidi_command(*page, command_id, navigable_id, method, move(params));
+}
+
+void ConnectionFromClient::set_webdriver_bidi_session_state(Web::WebDriver::BiDiSessionState state)
+{
+ WebContent::set_webdriver_bidi_session_state(move(state));
+}
+
void ConnectionFromClient::set_webdriver_session_config(Web::PageId page_id, Web::WebDriver::UserPromptHandler user_prompt_handler, Web::WebDriver::PageLoadStrategy page_load_strategy, bool strict_file_interactability, JsonValue timeouts)
{
if (auto page = this->page(page_id); page.has_value())
diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.h
index a1a821423e0..4c676c5a01d 100644
--- a/Services/WebContent/ConnectionFromClient.h
+++ b/Services/WebContent/ConnectionFromClient.h
@@ -107,6 +107,8 @@ private:
virtual Messages::WebContentServer::GetWindowHandleResponse get_window_handle(Web::PageId page_id) override;
virtual void set_window_handle(Web::PageId page_id, String handle) override;
virtual void run_webdriver_command(Web::PageId page_id, u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String name, JsonValue payload, Vector<String> arguments) override;
+ virtual void run_webdriver_bidi_command(Web::PageId page_id, u64 command_id, Web::HTML::CrossProcessId navigable_id, String method, JsonValue params) override;
+ virtual void set_webdriver_bidi_session_state(Web::WebDriver::BiDiSessionState state) override;
virtual void set_webdriver_session_config(Web::PageId page_id, Web::WebDriver::UserPromptHandler user_prompt_handler, Web::WebDriver::PageLoadStrategy page_load_strategy, bool strict_file_interactability, JsonValue timeouts) override;
virtual void run_webdriver_user_prompt_handling(Web::PageId page_id, u64 request_id) override;
virtual void did_handle_webdriver_mouse_event(Web::PageId page_id, u64 request_id) override;
diff --git a/Services/WebContent/DevToolsConsoleClient.cpp b/Services/WebContent/DevToolsConsoleClient.cpp
index 467d2d7b57c..90627a32ab6 100644
--- a/Services/WebContent/DevToolsConsoleClient.cpp
+++ b/Services/WebContent/DevToolsConsoleClient.cpp
@@ -16,6 +16,7 @@
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/Window.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
#include <WebContent/ConsoleGlobalEnvironmentExtensions.h>
#include <WebContent/DevToolsConsoleClient.h>
#include <WebContent/PageClient.h>
@@ -144,6 +145,10 @@ void DevToolsConsoleClient::send_console_output(WebView::ConsoleOutput console_o
// 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)
{
+ // https://w3c.github.io/webdriver-bidi/#event-log-entryAdded
+ if (Web::WebDriver::BiDi::is_active())
+ Web::WebDriver::BiDi::console_steps(Web::HTML::principal_realm_settings_object(m_console->realm()), log_level, arguments);
+
if (log_level == JS::Console::LogLevel::Trace) {
auto const& trace = arguments.get<JS::Console::Trace>();
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index f3be63bdd0b..50b099d5834 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -57,6 +57,7 @@
#include <LibWeb/Painting/DocumentPaintState.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Streams/ReadableStreamDefaultReader.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
#include <LibWeb/WebDriver/UserPrompt.h>
#include <LibWeb/WebIDL/Promise.h>
#include <LibWebCommon/HTML/NavigationPopulationRequest.h>
@@ -216,7 +217,16 @@ void PageClient::set_has_focus(bool has_focus)
void PageClient::set_window_handle(Utf16String window_handle)
{
- as<Web::HTML::LocalTraversableNavigable>(*page().top_level_traversable()).set_window_handle(move(window_handle));
+ auto& traversable = as<Web::HTML::LocalTraversableNavigable>(*page().top_level_traversable());
+ auto first_window_handle = traversable.window_handle().is_empty();
+ traversable.set_window_handle(move(window_handle));
+
+ // NB: The initial page gets its window handle after its first document becomes active. The window-open path
+ // assigns its handle and runs these steps while creating the traversable instead.
+ if (first_window_handle && Web::WebDriver::BiDi::is_active()) {
+ if (auto document = traversable.active_document(); document && document->is_initial_about_blank())
+ Web::WebDriver::BiDi::document_is_ready_for_scripts(*document);
+ }
}
void PageClient::setup_palette()
@@ -2127,6 +2137,16 @@ void PageClient::webdriver_command_complete(u64 command_id, Web::WebDriver::Resp
client().async_webdriver_command_complete(m_id, command_id, move(response));
}
+void PageClient::webdriver_bidi_event(Web::HTML::CrossProcessId navigable_id, String const& name, JsonValue params)
+{
+ client().async_webdriver_bidi_event(m_id, navigable_id, name, move(params));
+}
+
+void PageClient::webdriver_bidi_navigation_event(Web::HTML::CrossProcessId navigable_id, StringView name, Optional<Utf16String> const& navigation_id, URL::URL const& url)
+{
+ client().async_webdriver_bidi_navigation_event(m_id, navigable_id, MUST(String::from_utf8(name)), navigation_id, url);
+}
+
void PageClient::set_webdriver_session_config(Web::WebDriver::UserPromptHandler user_prompt_handler, Web::WebDriver::PageLoadStrategy page_load_strategy, bool strict_file_interactability, JsonValue const& timeouts)
{
Web::WebDriver::set_user_prompt_handler(move(user_prompt_handler));
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index 286b10bec53..8a296b1ebe3 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -63,6 +63,8 @@ public:
void webdriver_did_set_current_browsing_context(u64 command_id, Web::HTML::CrossProcessId navigable_id);
void did_handle_webdriver_mouse_event(u64 request_id);
void webdriver_command_complete(u64 command_id, Web::WebDriver::Response);
+ void webdriver_bidi_event(Web::HTML::CrossProcessId navigable_id, String const& name, JsonValue params);
+ void webdriver_bidi_navigation_event(Web::HTML::CrossProcessId navigable_id, StringView name, Optional<Utf16String> const& navigation_id, URL::URL const&);
void set_webdriver_session_config(Web::WebDriver::UserPromptHandler, Web::WebDriver::PageLoadStrategy, bool strict_file_interactability, JsonValue const& timeouts);
ErrorOr<void> connect_to_web_ui(IPC::TransportHandle);
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index cbcdb423fc5..2a7370a277d 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -215,6 +215,8 @@ endpoint WebContentClient routed by Web::PageId page_id
webdriver_user_prompt_handling_complete(Web::PageId page_id, u64 request_id, Web::WebDriver::Response response) =|
webdriver_did_set_current_browsing_context(Web::PageId page_id, u64 command_id, Web::HTML::CrossProcessId navigable_id) =|
webdriver_command_complete(Web::PageId page_id, u64 command_id, Web::WebDriver::Response response) =|
+ webdriver_bidi_event(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, String name, JsonValue params) =|
+ webdriver_bidi_navigation_event(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, String name, Optional<Utf16String> navigation_id, URL::URL url) =|
did_request_restore_window(Web::PageId page_id) =|
did_request_reposition_window(Web::PageId page_id, Gfx::IntPoint position, u64 completion_id) =|
did_request_resize_window(Web::PageId page_id, Gfx::IntSize size, u64 completion_id) =|
diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipc
index fe0854a2fe7..3fcf8dfafa8 100644
--- a/Services/WebContent/WebContentServer.ipc
+++ b/Services/WebContent/WebContentServer.ipc
@@ -52,6 +52,7 @@
#include <LibWebCommon/ReferrerPolicy/ReferrerPolicy.h>
#include <LibWebCommon/StorageAPI/StorageAreaId.h>
#include <LibWebCommon/StorageAPI/StorageEndpoint.h>
+#include <LibWebCommon/WebDriver/BiDi.h>
#include <LibWebCommon/WebDriver/Capabilities.h>
#include <LibWebCommon/WebDriver/Response.h>
#include <LibWebCommon/WebDriver/UserPrompt.h>
@@ -84,6 +85,8 @@ endpoint WebContentServer routed by Web::PageId page_id
run_webdriver_user_prompt_handling(Web::PageId page_id, u64 request_id) =|
did_handle_webdriver_mouse_event(Web::PageId page_id, u64 request_id) =|
set_webdriver_session_config(Web::PageId page_id, Web::WebDriver::UserPromptHandler user_prompt_handler, Web::WebDriver::PageLoadStrategy page_load_strategy, bool strict_file_interactability, JsonValue timeouts) =|
+ run_webdriver_bidi_command(Web::PageId page_id, u64 command_id, Web::HTML::CrossProcessId navigable_id, String method, JsonValue params) =|
+ set_webdriver_bidi_session_state(Web::WebDriver::BiDiSessionState state) =|
connect_to_web_ui(Web::PageId page_id, IPC::TransportHandle handle) =|
connect_to_request_server(IPC::TransportHandle handle, int client_id) =|
connect_to_test_endpoint(IPC::TransportHandle handle) =|
diff --git a/Services/WebContent/WebDriverBiDi.cpp b/Services/WebContent/WebDriverBiDi.cpp
new file mode 100644
index 00000000000..26871450f9b
--- /dev/null
+++ b/Services/WebContent/WebDriverBiDi.cpp
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/JsonObject.h>
+#include <LibGC/Root.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/HTML/LocalNavigable.h>
+#include <LibWeb/HTML/LocalTraversableNavigable.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/HTML/Window.h>
+#include <LibWeb/Page/Page.h>
+#include <LibWeb/WebDriver/BiDi/BiDi.h>
+#include <LibWeb/WebDriver/BiDi/Script.h>
+#include <WebContent/ConnectionFromClient.h>
+#include <WebContent/PageClient.h>
+#include <WebContent/WebDriverBiDi.h>
+
+namespace WebContent {
+
+static Web::WebDriver::Error no_such_frame()
+{
+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, "Browsing context not found"sv);
+}
+
+static PageClient* page_client_of(Web::HTML::Navigable const& navigable)
+{
+ return as_if<PageClient>(const_cast<Web::HTML::Navigable&>(navigable).page().client());
+}
+
+void set_webdriver_bidi_session_state(Web::WebDriver::BiDiSessionState state)
+{
+ // NB: Events of the navigables this process hosts go to the page hosting them, which reports them to the browser
+ // process.
+ if (state.is_active && !Web::WebDriver::BiDi::is_active()) {
+ Web::WebDriver::BiDi::set_event_sink({
+ .on_event = [](Web::HTML::Navigable const& navigable, String const& name, JsonValue params) {
+ if (auto* page_client = page_client_of(navigable))
+ page_client->webdriver_bidi_event(navigable.id(), name, move(params)); },
+ .on_navigation_event = [](Web::HTML::Navigable const& navigable, StringView name, Optional<Utf16String> const& navigation_id, URL::URL const& url) {
+ if (auto* page_client = page_client_of(navigable))
+ page_client->webdriver_bidi_navigation_event(navigable.id(), name, navigation_id, url); },
+ });
+ }
+
+ Web::WebDriver::BiDi::set_session_state(move(state));
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-browsingContext-create
+static Web::WebDriver::Response create_a_new_top_level_traversable(Web::HTML::Navigable& navigable)
+{
+ // 11. Let traversable be the result of trying to create a new top-level traversable steps with null, empty string,
+ // null, and false, and setting the associated user context for the newly created top-level traversable to user
+ // context.
+ // NB: The window open steps create it without an opener, the way WebDriver's New Window command does.
+ auto* local_navigable = as_if<Web::HTML::LocalNavigable>(navigable);
+ if (!local_navigable || !local_navigable->active_window())
+ return no_such_frame();
+
+ auto& active_window = *local_navigable->active_window();
+ Web::HTML::TemporaryExecutionContext execution_context { active_window.document()->relevant_settings_object() };
+ auto opened_window = active_window.window_open_steps_internal(u"about:blank"sv, u""sv, u"noopener"sv);
+ if (opened_window.is_error() || !opened_window.value().navigable)
+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnsupportedOperation, "Unable to create a top-level traversable"sv);
+
+ auto traversable = opened_window.value().navigable->traversable_navigable();
+ auto const* local_traversable = as_if<Web::HTML::LocalTraversableNavigable>(*traversable);
+ if (!local_traversable)
+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnsupportedOperation, "Unable to create a top-level traversable"sv);
+
+ JsonObject result;
+ result.set("context"sv, local_traversable->window_handle().to_utf8());
+ return JsonValue { move(result) };
+}
+
+void run_webdriver_bidi_command(PageClient& page_client, u64 command_id, Web::HTML::CrossProcessId navigable_id, String const& method, JsonValue params_value)
+{
+ auto on_complete = [page_client = GC::make_root(page_client), command_id](Web::WebDriver::Response response) {
+ page_client->webdriver_command_complete(command_id, move(response));
+ };
+
+ auto navigable = page_client.page().navigable_with_id(navigable_id);
+ if (!navigable) {
+ on_complete(no_such_frame());
+ return;
+ }
+ if (!params_value.is_object()) {
+ on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Command parameters must be an object"sv));
+ return;
+ }
+ auto const& params = params_value.as_object();
+
+ if (method == "script.evaluate"sv)
+ return Web::WebDriver::BiDi::evaluate(*navigable, params, move(on_complete));
+ if (method == "script.callFunction"sv)
+ return Web::WebDriver::BiDi::call_function(*navigable, params, move(on_complete));
+ if (method == "script.disown"sv)
+ return on_complete(Web::WebDriver::BiDi::disown(*navigable, params));
+ if (method == "script.getRealms"sv)
+ return on_complete(Web::WebDriver::BiDi::get_realms(*navigable, params));
+ if (method == "browsingContext.create"sv)
+ return on_complete(create_a_new_top_level_traversable(*navigable));
+
+ on_complete(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownCommand, "Command is not supported"sv));
+}
+
+}
diff --git a/Services/WebContent/WebDriverBiDi.h b/Services/WebContent/WebDriverBiDi.h
new file mode 100644
index 00000000000..657adf3bd79
--- /dev/null
+++ b/Services/WebContent/WebDriverBiDi.h
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/JsonValue.h>
+#include <AK/String.h>
+#include <LibWebCommon/HTML/CrossProcessId.h>
+#include <LibWebCommon/WebDriver/BiDi.h>
+#include <WebContent/Forward.h>
+
+namespace WebContent {
+
+// https://w3c.github.io/webdriver-bidi/#commands
+// NB: Runs a command of a BiDi session against a navigable this page hosts, which the browser process names.
+void run_webdriver_bidi_command(PageClient&, u64 command_id, Web::HTML::CrossProcessId navigable_id, String const& method, JsonValue params);
+
+void set_webdriver_bidi_session_state(Web::WebDriver::BiDiSessionState);
+
+}
diff --git a/Services/WebDriver/BiDiSession.cpp b/Services/WebDriver/BiDiSession.cpp
new file mode 100644
index 00000000000..bd378688241
--- /dev/null
+++ b/Services/WebDriver/BiDiSession.cpp
@@ -0,0 +1,1239 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/AllOf.h>
+#include <AK/AnyOf.h>
+#include <AK/Array.h>
+#include <AK/JsonArray.h>
+#include <AK/JsonObject.h>
+#include <AK/NeverDestroyed.h>
+#include <AK/QuickSort.h>
+#include <AK/Random.h>
+#include <AK/ScopeGuard.h>
+#include <LibCore/EventLoop.h>
+#include <LibWebCommon/WebDriver/BiDi.h>
+#include <WebDriver/BiDiSession.h>
+#include <WebDriver/Session.h>
+
+// Failures become rejected promises rather than propagated ErrorOr values, so this macro may only be used in functions
+// returning a WebDriverPromise.
+#define TRY_OR_REJECT(expression) \
+ ({ \
+ /* Ignore -Wshadow to allow nesting the macro. */ \
+ AK_IGNORE_DIAGNOSTIC("-Wshadow", \
+ auto&& _temporary_result = (expression)); \
+ static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
+ "Do not return a reference from a fallible expression"); \
+ if (_temporary_result.is_error()) [[unlikely]] { \
+ return WebDriverPromise::rejected(_temporary_result.release_error()); \
+ } \
+ _temporary_result.release_value(); \
+ })
+
+namespace WebDriver {
+
+// https://w3c.github.io/webdriver-bidi/#set-of-all-command-names
+static constexpr auto s_command_names = to_array<StringView>({
+ "browser.close"sv,
+ "browser.createUserContext"sv,
+ "browser.getClientWindows"sv,
+ "browser.getUserContexts"sv,
+ "browser.removeUserContext"sv,
+ "browser.setClientWindowState"sv,
+ "browser.setDownloadBehavior"sv,
+ "browsingContext.activate"sv,
+ "browsingContext.captureScreenshot"sv,
+ "browsingContext.close"sv,
+ "browsingContext.create"sv,
+ "browsingContext.getTree"sv,
+ "browsingContext.handleUserPrompt"sv,
+ "browsingContext.locateNodes"sv,
+ "browsingContext.navigate"sv,
+ "browsingContext.print"sv,
+ "browsingContext.reload"sv,
+ "browsingContext.setBypassCSP"sv,
+ "browsingContext.setViewport"sv,
+ "browsingContext.startScreencast"sv,
+ "browsingContext.stopScreencast"sv,
+ "browsingContext.traverseHistory"sv,
+ "emulation.setForcedColorsModeThemeOverride"sv,
+ "emulation.setGeolocationOverride"sv,
+ "emulation.setLocaleOverride"sv,
+ "emulation.setMediaFeaturesOverride"sv,
+ "emulation.setNetworkConditions"sv,
+ "emulation.setScreenSettingsOverride"sv,
+ "emulation.setScreenOrientationOverride"sv,
+ "emulation.setUserAgentOverride"sv,
+ "emulation.setViewportMetaOverride"sv,
+ "emulation.setScriptingEnabled"sv,
+ "emulation.setScrollbarTypeOverride"sv,
+ "emulation.setTextLayoutModeOverride"sv,
+ "emulation.setTimezoneOverride"sv,
+ "emulation.setTouchOverride"sv,
+ "input.performActions"sv,
+ "input.releaseActions"sv,
+ "input.setFiles"sv,
+ "network.addDataCollector"sv,
+ "network.addIntercept"sv,
+ "network.continueRequest"sv,
+ "network.continueResponse"sv,
+ "network.continueWithAuth"sv,
+ "network.disownData"sv,
+ "network.failRequest"sv,
+ "network.getData"sv,
+ "network.provideResponse"sv,
+ "network.removeDataCollector"sv,
+ "network.removeIntercept"sv,
+ "network.setCacheBehavior"sv,
+ "network.setExtraHeaders"sv,
+ "script.addPreloadScript"sv,
+ "script.callFunction"sv,
+ "script.disown"sv,
+ "script.evaluate"sv,
+ "script.getRealms"sv,
+ "script.removePreloadScript"sv,
+ "session.end"sv,
+ "session.new"sv,
+ "session.status"sv,
+ "session.subscribe"sv,
+ "session.unsubscribe"sv,
+ "storage.deleteCookies"sv,
+ "storage.getCookies"sv,
+ "storage.setCookie"sv,
+ "webExtension.install"sv,
+ "webExtension.uninstall"sv,
+});
+
+// https://w3c.github.io/webdriver-bidi/#module-name
+static constexpr auto s_module_names = to_array<StringView>({
+ "browser"sv,
+ "browsingContext"sv,
+ "emulation"sv,
+ "input"sv,
+ "log"sv,
+ "network"sv,
+ "script"sv,
+ "session"sv,
+ "storage"sv,
+ "webExtension"sv,
+});
+
+// https://w3c.github.io/webdriver-bidi/#event-name
+static constexpr auto s_event_names = to_array<StringView>({
+ "browsingContext.contextCreated"sv,
+ "browsingContext.contextDestroyed"sv,
+ "browsingContext.domContentLoaded"sv,
+ "browsingContext.downloadEnd"sv,
+ "browsingContext.downloadWillBegin"sv,
+ "browsingContext.fragmentNavigated"sv,
+ "browsingContext.historyUpdated"sv,
+ "browsingContext.load"sv,
+ "browsingContext.navigationAborted"sv,
+ "browsingContext.navigationCommitted"sv,
+ "browsingContext.navigationFailed"sv,
+ "browsingContext.navigationStarted"sv,
+ "browsingContext.userPromptClosed"sv,
+ "browsingContext.userPromptOpened"sv,
+ "input.fileDialogOpened"sv,
+ "log.entryAdded"sv,
+ "network.authRequired"sv,
+ "network.beforeRequestSent"sv,
+ "network.fetchError"sv,
+ "network.responseCompleted"sv,
+ "network.responseStarted"sv,
+ "script.message"sv,
+ "script.realmCreated"sv,
+ "script.realmDestroyed"sv,
+});
+
+// https://w3c.github.io/webdriver-bidi/#remote-end-subscribe-steps
+// NB: The events that define remote end subscribe steps, with their subscribe priority.
+struct EventWithSubscribeSteps {
+ StringView name;
+ int subscribe_priority;
+};
+static constexpr auto s_events_with_subscribe_steps = to_array<EventWithSubscribeSteps>({
+ { "browsingContext.contextCreated"sv, 1 },
+ { "script.realmCreated"sv, 2 },
+ { "log.entryAdded"sv, 10 },
+});
+
+// https://w3c.github.io/webdriver-bidi/#log-event-buffer
+// User agents may impose a maximum size on this buffer, subject to the condition that if events A and B happen in the
+// same context with A occurring before B, and both are added to the buffer, the entry for B must not be removed before
+// the entry for A.
+static constexpr size_t MAXIMUM_LOG_EVENT_BUFFER_SIZE = 1000;
+
+// NB: Web content decides how large its log events are, so the events buffered for a navigable are bounded in bytes
+// too.
+static constexpr size_t MAXIMUM_LOG_EVENT_BUFFER_BYTES = 16 * MiB;
+
+static Optional<int> subscribe_priority(StringView event_name)
+{
+ for (auto const& event : s_events_with_subscribe_steps) {
+ if (event.name == event_name)
+ return event.subscribe_priority;
+ }
+ return {};
+}
+
+// https://w3c.github.io/webdriver-bidi/#default-user-context
+// FIXME: Support user contexts other than the default user context.
+static constexpr auto DEFAULT_USER_CONTEXT_ID = "default"sv;
+
+// NB: A response of the browser process that does not have the form of the result of its command.
+static Web::WebDriver::Error invalid_browser_response()
+{
+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Invalid response from the browser"sv);
+}
+
+static Web::WebDriver::Error invalid_argument(StringView message)
+{
+ return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, message);
+}
+
+// https://w3c.github.io/webdriver-bidi/#obtain-a-set-of-event-names
+static ErrorOr<HashTable<String>, Web::WebDriver::Error> obtain_a_set_of_event_names(String const& name)
+{
+ // 1. Let events be an empty set.
+ HashTable<String> events;
+
+ // 2. If name contains a U+002E (period):
+ if (name.contains('.')) {
+ // 1. If name is the event name for an event, append name to events and return success with data events.
+ if (any_of(s_event_names, [&](auto event_name) { return event_name == name; })) {
+ events.set(name);
+ return events;
+ }
+
+ // 2. Return an error with error code invalid argument
+ return invalid_argument("Unknown event name"sv);
+ }
+
+ // 3. Otherwise name is interpreted as representing all the events in a module. If name is not a module name return
+ // an error with error code invalid argument.
+ if (!any_of(s_module_names, [&](auto module_name) { return module_name == name; }))
+ return invalid_argument("Unknown module name"sv);
+
+ // 4. Append the event name for each event in the module with name name to events.
+ for (auto event_name : s_event_names) {
+ if (event_name.starts_with(name) && event_name.length() > name.bytes_as_string_view().length() && event_name[name.bytes_as_string_view().length()] == '.')
+ events.set(MUST(String::from_utf8(event_name)));
+ }
+
+ // 5. Return success with data events.
+ return events;
+}
+
+static bool sets_are_equal(HashTable<String> const& a, HashTable<String> const& b)
+{
+ return a.size() == b.size() && all_of(a, [&](auto const& item) { return b.contains(item); });
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-a-session-id-for-a-websocket-resource
+static Optional<StringView> get_a_session_id_for_a_websocket_resource(StringView resource_name)
+{
+ // 1. If resource name doesn't begin with the byte string "/session/", return null.
+ if (!resource_name.starts_with("/session/"sv))
+ return {};
+
+ // 2. Let session id be the bytes in resource name following the "/session/" prefix.
+ auto session_id = resource_name.substring_view("/session/"sv.length());
+
+ // 3. If session id is not the string representation of a UUID, return null.
+ if (session_id.length() != 36)
+ return {};
+ for (size_t i = 0; i < session_id.length(); ++i) {
+ if (i == 8 || i == 13 || i == 18 || i == 23) {
+ if (session_id[i] != '-')
+ return {};
+ } else if (!is_ascii_hex_digit(session_id[i])) {
+ return {};
+ }
+ }
+
+ // 4. Return session id.
+ return session_id;
+}
+
+// https://w3c.github.io/webdriver-bidi/#active-listeners
+// NB: An endpoint node supports one session at a time, so a single listener serves every session.
+static OwnPtr<WebSocketListener>& websocket_listener()
+{
+ static NeverDestroyed<OwnPtr<WebSocketListener>> listener;
+ return *listener;
+}
+
+// https://w3c.github.io/webdriver-bidi/#websocket-connections-not-associated-with-a-session
+// NB: We do not support BiDi-only sessions, so this only holds connections whose opening handshake is not complete.
+static Vector<NonnullRefPtr<WebSocketConnection>>& connections_awaiting_opening_handshake()
+{
+ static NeverDestroyed<Vector<NonnullRefPtr<WebSocketConnection>>> connections;
+ return *connections;
+}
+
+// NB: The connections whose closing handshake we started, until it completes.
+static Vector<NonnullRefPtr<WebSocketConnection>>& closing_connections()
+{
+ static NeverDestroyed<Vector<NonnullRefPtr<WebSocketConnection>>> connections;
+ return *connections;
+}
+
+// NB: A WebDriver client opens one connection at a time. This bounds the connections that other local processes can
+// keep open without completing an opening handshake.
+static constexpr size_t MAXIMUM_CONNECTIONS_AWAITING_OPENING_HANDSHAKE = 16;
+
+BiDiSession::BiDiSession(Session& session)
+ : m_session(session)
+{
+}
+
+BiDiSession::~BiDiSession()
+{
+ close_the_websocket_connections();
+}
+
+// https://w3c.github.io/webdriver-bidi/#start-listening-for-a-websocket-connection
+ErrorOr<String> BiDiSession::start_listening_for_a_websocket_connection(Session const& session)
+{
+ // 1. If there is an existing WebSocket listener in active listeners which the remote end would like to reuse, let
+ // listener be that listener. Otherwise let listener be a new WebSocket listener with implementation-defined host,
+ // port, secure flag, and an empty list of WebSocket resources.
+ if (!websocket_listener()) {
+ websocket_listener() = TRY(WebSocketListener::create());
+ websocket_listener()->on_connection = [](NonnullRefPtr<WebSocketConnection> connection) {
+ if (connections_awaiting_opening_handshake().size() >= MAXIMUM_CONNECTIONS_AWAITING_OPENING_HANDSHAKE)
+ return;
+ connection->on_opening_handshake = [connection = connection.ptr()](StringView resource_name) {
+ connections_awaiting_opening_handshake().remove_all_matching([&](auto const& other) { return other.ptr() == connection; });
+ return accept_connection(*connection, resource_name);
+ };
+ connection->on_close = [connection = connection.ptr()] {
+ connections_awaiting_opening_handshake().remove_all_matching([&](auto const& other) { return other.ptr() == connection; });
+ };
+ connections_awaiting_opening_handshake().append(move(connection));
+ };
+ }
+
+ // 2. Let resource name be the result of construct a WebSocket resource name with session.
+ // 3. Append resource name to the list of WebSocket resources for listener.
+ // 4. Append listener to the remote end's active listeners.
+ // NB: The listener accepts a connection for the resource name of any active BiDi session.
+
+ // https://w3c.github.io/webdriver-bidi/#construct-a-websocket-url
+ // 1. Let resource name be the result of construct a WebSocket resource name with session.
+ // 2. Return a WebSocket URI constructed with host set to listener's host, port set to listener's port, path set to
+ // resource name, following the wss-URI construct if listener's secure flag is set and the ws-URL construct
+ // otherwise.
+ return String::formatted("ws://127.0.0.1:{}/session/{}", websocket_listener()->port(), session.session_id());
+}
+
+// https://w3c.github.io/webdriver-bidi/#establishing
+bool BiDiSession::accept_connection(WebSocketConnection& connection, StringView resource_name)
+{
+ // 1. Let resource name be the resource name from reading the client's opening handshake. If resource name is not in
+ // listener's list of WebSocket resources, then stop running these steps and act as if the requested service is not
+ // available.
+ // 2. If resource name is the byte string "/session", and the implementation supports BiDi-only sessions:
+ // NB: We do not support BiDi-only sessions.
+
+ // 3. Get a session ID for a WebSocket resource with resource name and let session id be that value. If session id is
+ // null then stop running these steps and act as if the requested service is not available.
+ auto session_id = get_a_session_id_for_a_websocket_resource(resource_name);
+ if (!session_id.has_value())
+ return false;
+
+ // 4. If there is a session in the list of active sessions with session id as its session ID then let session be
+ // that session. Otherwise stop running these steps and act as if the requested service is not available.
+ auto session = Session::find_session(*session_id, Web::WebDriver::SessionFlags::Default, Session::AllowInvalidWindowHandle::Yes);
+ if (session.is_error() || !session.value()->bidi_session())
+ return false;
+
+ // 5. Run any other implementation-defined steps to decide if the connection should be accepted, and if it is not stop
+ // running these steps and act as if the requested service is not available.
+ // NB: The WebSocket layer only accepts connections from the local machine that are not made by web content. A
+ // session also accepts a single connection, so that once the WebDriver client is connected, nothing else can
+ // connect to its session.
+ if (!session.value()->bidi_session()->m_session_websocket_connections.is_empty())
+ return false;
+
+ // 6. Otherwise append connection to session's session WebSocket connections, and proceed with the WebSocket
+ // server-side requirements when a server chooses to accept an incoming connection.
+ session.value()->bidi_session()->add_connection(connection);
+ return true;
+}
+
+void BiDiSession::add_connection(NonnullRefPtr<WebSocketConnection> connection)
+{
+ connection->on_message = [this, connection = connection.ptr()](WebSocketConnection::MessageType type, ByteBuffer data) {
+ // When a WebSocket message has been received for a WebSocket connection connection with type type and data
+ // data, a remote end must handle an incoming message given connection, type and data.
+ handle_an_incoming_message(*connection, type, move(data));
+ };
+ connection->on_close = [this, connection = connection.ptr()] {
+ // When the WebSocket closing handshake is started or when the WebSocket connection is closed for a WebSocket
+ // connection connection, a remote end must handle a connection closing given connection.
+ handle_a_connection_closing(*connection);
+ };
+ m_session_websocket_connections.append(move(connection));
+}
+
+// https://w3c.github.io/webdriver-bidi/#handle-a-connection-closing
+void BiDiSession::handle_a_connection_closing(WebSocketConnection& connection)
+{
+ // 1. If there is a BiDi session associated with connection connection:
+ // 1. Let session be the BiDi session associated with connection connection.
+ // 2. Remove connection from session's session WebSocket connections.
+ m_session_websocket_connections.remove_all_matching([&](auto const& other) { return other.ptr() == &connection; });
+
+ // NB: This does not end any session.
+}
+
+// https://w3c.github.io/webdriver-bidi/#close-the-websocket-connections
+void BiDiSession::close_the_websocket_connections()
+{
+ // 1. For each connection in session's session WebSocket connections:
+ auto connections = move(m_session_websocket_connections);
+ for (auto& connection : connections) {
+ // 1. Start the WebSocket closing handshake with connection.
+ connection->on_message = nullptr;
+ connection->on_close = [connection = connection.ptr()] {
+ closing_connections().remove_all_matching([&](auto const& other) { return other.ptr() == connection; });
+ };
+ connection->start_the_closing_handshake();
+ closing_connections().append(connection);
+ }
+}
+
+// https://w3c.github.io/webdriver-bidi/#handle-an-incoming-message
+void BiDiSession::handle_an_incoming_message(WebSocketConnection& connection, WebSocketConnection::MessageType type, ByteBuffer data)
+{
+ // 1. If type is not text, send an error response given connection, null, and invalid argument, and finally return.
+ if (type != WebSocketConnection::MessageType::Text) {
+ send_an_error_response(connection, {}, invalid_argument("Messages must be text"sv));
+ return;
+ }
+
+ // 2. Assert: data is a scalar value string, because the WebSocket handling errors in UTF-8-encoded data would already
+ // have failed the WebSocket connection otherwise.
+
+ // 3. If there is a BiDi Session associated with connection connection, let session be that session. Otherwise if
+ // connection is in WebSocket connections not associated with a session, let session be null. Otherwise, return.
+ // NB: Every connection we handle messages for is associated with this session.
+
+ // 4. Let parsed be the result of parsing JSON into Infra values given data. If this throws an exception, then send
+ // an error response given connection, null, and invalid argument, and finally return.
+ auto parsed = JsonValue::from_string(StringView { data.bytes() });
+ if (parsed.is_error()) {
+ send_an_error_response(connection, {}, invalid_argument("Message is not valid JSON"sv));
+ return;
+ }
+
+ // 5. If session is not null and not in active sessions then return.
+ // NB: A session that session.end ended is no longer active, even though it is cleaned up after the response.
+ if (!m_session.is_active() || m_has_ended)
+ return;
+
+ // 6. Match parsed against the remote end definition. If this results in a match:
+ // Command = { id: js-uint, CommandData, Extensible }
+ // NB: Each command's remote end steps check its params against its own production.
+ Optional<JsonValue const&> id;
+ Optional<String> method;
+ Optional<JsonValue const&> params;
+ if (parsed.value().is_object()) {
+ auto const& command = parsed.value().as_object();
+ id = command.get("id"sv);
+ if (auto method_name = command.get_string("method"sv); method_name.has_value())
+ method = *method_name;
+ params = command.get("params"sv);
+ }
+
+ bool matches = id.has_value() && Web::WebDriver::as_js_uint(*id).has_value()
+ && method.has_value() && any_of(s_command_names, [&](auto name) { return name == *method; })
+ && params.has_value() && params->is_object();
+
+ if (matches) {
+ // 1. Let matched be the map representing the matched data.
+ // 2. Assert: matched contains "id", "method", and "params".
+ // 3. Let command id be matched["id"].
+ auto command_id = *id;
+
+ // 4. Let method be matched["method"]
+ // 5. Let command be the command with command name method.
+ // 6. If session is null and command is not a static command, then send an error response given connection,
+ // command id, and invalid session id, and return.
+ // NB: Session is never null.
+
+ // 7. Run the following steps in parallel:
+ auto promise = run_command(*method, *params);
+ promise->when_resolved([this, connection = NonnullRefPtr { connection }, command_id, method = *method](JsonValue& value) mutable {
+ // 3. Let value be result's data.
+ // 4. Assert: value matches the definition for the result type corresponding to the command with
+ // command name method.
+ // NB: A command whose result type is EmptyResult completes with null.
+ if (value.is_null())
+ value = JsonObject {};
+
+ // 5. If method is "session.new", let session be the entry in the list of active sessions whose session ID
+ // is equal to the "sessionId" property of value, append connection to session's session WebSocket
+ // connections, and remove connection from the WebSocket connections not associated with a session.
+ // 6. Let response be a new map matching the CommandResponse production in the local end definition with
+ // the id field set to command id and the value field set to value.
+ // 7. Let serialized be the result of serialize an infra value to JSON bytes given response.
+ // 8. Send a WebSocket message comprised of serialized over connection.
+ send_a_success_response(*connection, move(command_id), move(value));
+
+ // https://w3c.github.io/webdriver-bidi/#command-session-end
+ // 2. Return success with data null, and in parallel run the following steps:
+ // 1. Wait until the Send a WebSocket message steps have been called with the response to this command.
+ // 2. Cleanup the session with session.
+ if (method == "session.end"sv) {
+ Core::deferred_invoke([session = NonnullRefPtr { m_session }] {
+ session->close();
+ });
+ }
+ })
+ .when_rejected([this, connection = NonnullRefPtr { connection }, command_id](Web::WebDriver::Error& error) mutable {
+ // 2. If result is an error, then send an error response given connection, command id, and result's
+ // error code, and finally return.
+ send_an_error_response(*connection, move(command_id), error);
+ });
+ return;
+ }
+
+ // 7. Otherwise:
+ // 1. Let command id be null.
+ JsonValue command_id;
+
+ // 2. If parsed is a map and parsed["id"] exists and is an integer greater than or equal to zero, set command id to
+ // that integer.
+ if (id.has_value() && Web::WebDriver::as_js_uint(*id).has_value())
+ command_id = *id;
+
+ // 3. Let error code be invalid argument.
+ auto error = invalid_argument("Message does not match the format of a command"sv);
+
+ // 4. If parsed is a map and parsed["method"] exists and is a string, but parsed["method"] is not in the set of all
+ // command names, set error code to unknown command.
+ if (method.has_value() && !any_of(s_command_names, [&](auto name) { return name == *method; }))
+ error = Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownCommand, "Unknown command"sv);
+
+ // 5. Send an error response given connection, command id, and error code.
+ send_an_error_response(connection, move(command_id), error);
+}
+
+NonnullRefPtr<BiDiSession::WebDriverPromise> BiDiSession::run_command(StringView method, JsonValue params)
+{
+ if (method == "session.status"sv)
+ return session_status();
+ if (method == "session.new"sv) {
+ // https://w3c.github.io/webdriver-bidi/#command-session-new
+ // 1. If session is not null, return an error with error code session not created.
+ return WebDriverPromise::rejected(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::SessionNotCreated, "A session already exists"sv));
+ }
+ if (method == "session.end"sv)
+ return session_end();
+ if (method == "session.subscribe"sv)
+ return session_subscribe(move(params));
+ if (method == "session.unsubscribe"sv)
+ return session_unsubscribe(move(params));
+
+ // NB: The browser process runs every command of the other modules.
+ return m_session.perform_bidi_browser_command(method, move(params));
+}
+
+// https://w3c.github.io/webdriver-bidi/#send-an-error-response
+void BiDiSession::send_an_error_response(WebSocketConnection& connection, JsonValue command_id, Web::WebDriver::Error const& error)
+{
+ // 1. Let error data be a new map matching the ErrorResponse production in the local end definition, with the id field
+ // set to command id, the error field set to error code, the message field set to an implementation-defined string
+ // containing a human-readable definition of the error that occurred and the stacktrace field optionally set to an
+ // implementation-defined string containing a stack trace report of the active stack frames at the time when the
+ // error occurred.
+ JsonObject error_data;
+ error_data.set("type"sv, "error"sv);
+ error_data.set("id"sv, move(command_id));
+ error_data.set("error"sv, error.error);
+ error_data.set("message"sv, error.message);
+
+ // 2. Let response be the result of serialize an infra value to JSON bytes given error data.
+ auto response = error_data.serialized();
+
+ // 3. Send a WebSocket message comprised of response over connection.
+ connection.send_text_message(response);
+}
+
+void BiDiSession::send_a_success_response(WebSocketConnection& connection, JsonValue command_id, JsonValue result)
+{
+ JsonObject response;
+ response.set("type"sv, "success"sv);
+ response.set("id"sv, move(command_id));
+ response.set("result"sv, move(result));
+
+ connection.send_text_message(response.serialized());
+}
+
+// https://w3c.github.io/webdriver-bidi/#emit-an-event
+void BiDiSession::emit_an_event(StringView name, JsonValue params)
+{
+ // 1. Assert: body matches the Event production.
+ JsonObject body;
+ body.set("type"sv, "event"sv);
+ body.set("method"sv, name);
+ body.set("params"sv, move(params));
+
+ // 2. Let serialized be the result of serialize an infra value to JSON bytes given body.
+ auto serialized = body.serialized();
+
+ // 3. For each connection in session's session WebSocket connections:
+ for (auto& connection : m_session_websocket_connections) {
+ // 1. Send a WebSocket message comprised of serialized over connection.
+ connection->send_text_message(serialized);
+ }
+}
+
+// https://w3c.github.io/webdriver-bidi/#event-is-enabled
+// NB: The browser process gives the top-level traversables and user contexts of the navigables an event relates to.
+bool BiDiSession::event_is_enabled(StringView event_name, Vector<String> const& top_level_traversable_ids, Vector<String> const& user_context_ids) const
+{
+ // 1. Let top-level traversables be get top-level traversables with navigables.
+
+ // 2. For each subscription in session's subscriptions:
+ for (auto const& subscription : m_subscriptions) {
+ // 1. If subscription's event names do not contains event name, continue.
+ if (!subscription.event_names.contains(event_name))
+ continue;
+
+ // 2. If subscription is global return true.
+ if (subscription.is_global())
+ return true;
+
+ // 3. If user context ids is not empty:
+ if (!subscription.user_context_ids.is_empty()) {
+ // 1. For each navigable in top-level traversables:
+ // 1. If subscription's user context ids contains navigable's associated user context's user context id,
+ // return true.
+ for (auto const& user_context_id : user_context_ids) {
+ if (subscription.user_context_ids.contains(user_context_id))
+ return true;
+ }
+ }
+ // 4. Otherwise:
+ else {
+ // 1. Let subscription top-level traversables be get navigables by ids with subscription's top-level
+ // traversable ids.
+ // 2. If the intersection of top-level traversables and subscription top-level traversables is not empty
+ // return true.
+ for (auto const& top_level_traversable_id : top_level_traversable_ids) {
+ if (subscription.top_level_traversable_ids.contains(top_level_traversable_id))
+ return true;
+ }
+ }
+ }
+
+ // 3. Return false.
+ return false;
+}
+
+// https://w3c.github.io/webdriver-bidi/#set-of-top-level-traversables-for-which-an-event-is-enabled
+HashTable<String> BiDiSession::set_of_top_level_traversables_for_which_an_event_is_enabled(StringView event_name) const
+{
+ // 1. Let result be a new set.
+ HashTable<String> result;
+
+ // 2. For each subscription in session's subscriptions:
+ for (auto const& subscription : m_subscriptions) {
+ // 1. If subscription's event names does not contain event name, continue.
+ if (!subscription.event_names.contains(event_name))
+ continue;
+
+ // 2. If subscription's is global:
+ if (subscription.is_global()) {
+ // 1. For each traversable in remote end's top-level traversables:
+ // 1. Append traversable to result.
+ for (auto const& traversable : m_session.top_level_traversable_ids())
+ result.set(traversable);
+
+ // 2. Break.
+ break;
+ }
+
+ // 3. Otherwise, if user context ids is not empty:
+ if (!subscription.user_context_ids.is_empty()) {
+ // 1. For each traversable in remote end's top-level traversables:
+ // 1. Append traversable to result if subscription's user context ids contains traversable's associated
+ // user context's user context id.
+ if (subscription.user_context_ids.contains(DEFAULT_USER_CONTEXT_ID)) {
+ for (auto const& traversable : m_session.top_level_traversable_ids())
+ result.set(traversable);
+ }
+ }
+ // 4. Otherwise:
+ else {
+ // 1. Let top-level traversables be get navigables by ids with subscription's top-level traversable ids.
+ // 2. Append each item of top-level traversables to result.
+ for (auto const& traversable : subscription.top_level_traversable_ids) {
+ if (m_session.top_level_traversable_ids().contains_slow(traversable))
+ result.set(traversable);
+ }
+ }
+ }
+
+ // 3. Return result.
+ return result;
+}
+
+// NB: The browser process only reports the events some subscription enables.
+void BiDiSession::update_enabled_events()
+{
+ HashTable<String> enabled_events;
+ for (auto const& subscription : m_subscriptions) {
+ for (auto const& event_name : subscription.event_names)
+ enabled_events.set(event_name);
+ }
+
+ if (sets_are_equal(enabled_events, m_enabled_events))
+ return;
+ m_enabled_events = move(enabled_events);
+
+ Vector<String> event_names;
+ for (auto const& event_name : m_enabled_events)
+ event_names.append(event_name);
+ m_session.set_bidi_enabled_events(move(event_names));
+}
+
+void BiDiSession::did_receive_event(String const& name, JsonValue params, Vector<String> const& top_level_traversable_ids, Vector<String> const& user_context_ids)
+{
+ // NB: The browser process names the events defined by this specification, whose parameters are maps.
+ if (!any_of(s_event_names, [&](auto event_name) { return event_name == name; }) || !params.is_object())
+ return;
+
+ Optional<String> destroyed_navigable_id;
+ if (name == "browsingContext.contextDestroyed"sv) {
+ if (auto context = params.as_object().get_string("context"sv); context.has_value())
+ destroyed_navigable_id = *context;
+ }
+ ScopeGuard remove_destroyed_navigable = [&] {
+ // https://w3c.github.io/webdriver-bidi/#event-browsingContext-contextDestroyed
+ // NB: This runs for the session whether or not it is subscribed to the event.
+ if (destroyed_navigable_id.has_value())
+ remove_destroyed_navigable_from_subscriptions(*destroyed_navigable_id);
+ };
+
+ // For each session in the set of sessions for which an event is enabled given event name and related navigables:
+ if (!event_is_enabled(name, top_level_traversable_ids, user_context_ids)) {
+ // https://w3c.github.io/webdriver-bidi/#event-log-entryAdded
+ // Otherwise, buffer a log event with session, related browsing contexts, and body.
+ if (name == "log.entryAdded"sv)
+ buffer_a_log_event(top_level_traversable_ids, move(params));
+ return;
+ }
+
+ // Emit an event with session and body.
+ emit_an_event(name, move(params));
+}
+
+void BiDiSession::did_close_top_level_traversable(String const& id)
+{
+ // NB: Events of a closed top-level traversable that are buffered are never emitted.
+ m_log_event_buffer.remove(id);
+
+ // NB: The browser process reports browsingContext.contextDestroyed only while an event of that name is enabled,
+ // and that event removes the navigable from the subscriptions then.
+ if (!m_enabled_events.contains("browsingContext.contextDestroyed"sv))
+ remove_destroyed_navigable_from_subscriptions(id);
+}
+
+// https://w3c.github.io/webdriver-bidi/#buffer-a-log-event
+// NB: The buffer is keyed by the top-level traversables of the navigables the event relates to, whose ids WebDriver
+// knows. The specification leaves open whether to key it on browsing contexts or top-level traversables.
+void BiDiSession::buffer_a_log_event(Vector<String> const& top_level_traversable_ids, JsonValue event)
+{
+ // 1. Let buffer be session's log event buffer.
+ // 2. Let navigable ids be a new list.
+ // 3. For each navigable of navigables:
+ // 1. Append the navigable id for navigable to navigable ids.
+ // 4. For each navigable id in navigable ids:
+ // NB: The other navigables an event relates to are only relevant for workers, which do not report log events yet.
+ auto event_size = event.serialized().byte_count();
+ for (auto const& navigable_id : top_level_traversable_ids) {
+ // 1. Let other navigables be an empty list
+ // 2. For each other id in navigable ids:
+ // 1. If other id is not equal to navigable id, append other id to other navigables.
+ // 3. If buffer does not contain navigable id, let buffer[navigable id] be a new list.
+ auto& buffer = m_log_event_buffer.ensure(navigable_id);
+
+ // 4. Append (event, other navigables) to buffer[navigable id].
+ if (event_size > MAXIMUM_LOG_EVENT_BUFFER_BYTES)
+ continue;
+ while (!buffer.events.is_empty() && (buffer.events.size() >= MAXIMUM_LOG_EVENT_BUFFER_SIZE || buffer.size + event_size > MAXIMUM_LOG_EVENT_BUFFER_BYTES))
+ buffer.size -= buffer.events.take_first().size;
+ buffer.events.append(BufferedLogEvent { .event = event, .size = event_size });
+ buffer.size += event_size;
+ }
+}
+
+// https://w3c.github.io/webdriver-bidi/#event-log-entryAdded
+void BiDiSession::run_log_entry_added_subscribe_steps(HashTable<String> const& navigables, bool include_global)
+{
+ // 1. For each navigable id → events in session's log event buffer:
+ Vector<String> navigable_ids_to_remove;
+ auto top_level_traversable_ids = m_session.top_level_traversable_ids();
+ for (auto& [navigable_id, buffer] : m_log_event_buffer) {
+ // 1. Let maybe context be the result of getting a navigable given navigable id.
+ // 2. If maybe context is an error, remove navigable id from log event buffer and continue.
+ if (!top_level_traversable_ids.contains_slow(navigable_id)) {
+ navigable_ids_to_remove.append(navigable_id);
+ continue;
+ }
+
+ // 3. Let navigable be maybe context's data
+ // 4. Let top level navigable be navigable's top-level traversable.
+ // 5. If include global is true and top level navigable is not in navigables, or if include global is false and
+ // top level navigable is in navigables:
+ // AD-HOC: This emits the events of the top-level traversables the subscription newly enables, which local ends
+ // expect, whether or not the subscription is global.
+ (void)include_global;
+ if (!navigables.contains(navigable_id))
+ continue;
+
+ // 1. For each (event, other navigables) in events:
+ for (auto& buffered_event : buffer.events) {
+ // 1. Emit an event with session and event.
+ emit_an_event("log.entryAdded"sv, move(buffered_event.event));
+
+ // 2. For each other context id in other navigables:
+ // 1. If log event buffer contains other context id, remove event from log event buffer[other context id].
+ }
+
+ // NB: An emitted event is not emitted again.
+ navigable_ids_to_remove.append(navigable_id);
+ }
+
+ for (auto const& navigable_id : navigable_ids_to_remove)
+ m_log_event_buffer.remove(navigable_id);
+}
+
+// https://w3c.github.io/webdriver-bidi/#event-browsingContext-contextDestroyed
+void BiDiSession::remove_destroyed_navigable_from_subscriptions(String const& id)
+{
+ // 3. Let subscriptions to remove be a set.
+ // 4. For each subscription in session's subscriptions:
+ // 1. If subscription's top-level traversable ids contains navigable's navigable id;
+ // 1. Remove navigable's navigable id from subscription's top-level traversable ids.
+ // 2. If subscription's top-level traversable ids is empty:
+ // 1. Append subscription to subscriptions to remove.
+ // 5. Remove subscriptions to remove from session's subscriptions.
+ m_subscriptions.remove_all_matching([&](auto& subscription) {
+ if (!subscription.top_level_traversable_ids.remove(id))
+ return false;
+ return subscription.top_level_traversable_ids.is_empty();
+ });
+ update_enabled_events();
+}
+
+// https://w3c.github.io/webdriver-bidi/#readiness-state
+static bool readiness_state()
+{
+ return Session::session_count(Web::WebDriver::SessionFlags::Http) == 0 && !Session::has_pending_http_session_creation();
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-session-status
+NonnullRefPtr<BiDiSession::WebDriverPromise> BiDiSession::session_status()
+{
+ auto ready = readiness_state();
+
+ // 1. Let body be a new map with the following properties:
+ // "ready"
+ // The remote end’s readiness state.
+ // "message"
+ // An implementation-defined string explaining the remote end’s readiness state.
+ JsonObject body;
+ body.set("ready"sv, ready);
+ body.set("message"sv, ready ? "Ready to accept a new session"sv : "Not ready to accept a new session"sv);
+
+ // 2. Return success with data body
+ return WebDriverPromise::resolved(JsonValue { move(body) });
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-session-end
+NonnullRefPtr<BiDiSession::WebDriverPromise> BiDiSession::session_end()
+{
+ // 1. End the session with session.
+ m_has_ended = true;
+
+ // 2. Return success with data null, and in parallel run the following steps:
+ // 1. Wait until the Send a WebSocket message steps have been called with the response to this command.
+ // 2. Cleanup the session with session.
+ // NB: The session closes once the response is sent.
+ return WebDriverPromise::resolved(JsonValue {});
+}
+
+static ErrorOr<Vector<String>, Web::WebDriver::Error> get_non_empty_list_of_strings(JsonObject const& params, StringView name)
+{
+ auto value = params.get(name);
+ if (!value.has_value() || !value->is_array() || value->as_array().is_empty())
+ return invalid_argument(MUST(String::formatted("Parameter '{}' must be a non-empty list of strings", name)));
+
+ Vector<String> result;
+ for (auto const& item : value->as_array().values()) {
+ if (!item.is_string())
+ return invalid_argument(MUST(String::formatted("Parameter '{}' must be a non-empty list of strings", name)));
+ result.append(item.as_string());
+ }
+ return result;
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-session-subscribe
+NonnullRefPtr<BiDiSession::WebDriverPromise> BiDiSession::session_subscribe(JsonValue params_value)
+{
+ // session.SubscribeParameters = {
+ // events: [+text],
+ // ? contexts: [+browsingContext.BrowsingContext],
+ // ? userContexts: [+browser.UserContext],
+ // }
+ auto const& params = params_value.as_object();
+ auto events = TRY_OR_REJECT(get_non_empty_list_of_strings(params, "events"sv));
+
+ Vector<String> contexts;
+ if (params.has("contexts"sv))
+ contexts = TRY_OR_REJECT(get_non_empty_list_of_strings(params, "contexts"sv));
+
+ Vector<String> user_contexts;
+ if (params.has("userContexts"sv))
+ user_contexts = TRY_OR_REJECT(get_non_empty_list_of_strings(params, "userContexts"sv));
+
+ // 1. Let event names be an empty set.
+ HashTable<String> event_names;
+
+ // 2. For each entry name in command parameters["events"], let event names be the union of event names and the
+ // result of trying to obtain a set of event names with name.
+ for (auto const& name : events) {
+ auto names = TRY_OR_REJECT(obtain_a_set_of_event_names(name));
+ for (auto& event_name : names)
+ event_names.set(move(event_name));
+ }
+
+ // 3. Let input user context ids be create a set with command parameters[userContexts].
+ HashTable<String> input_user_context_ids;
+ for (auto const& user_context : user_contexts)
+ input_user_context_ids.set(user_context);
+
+ // 4. Let input context ids be create a set with command parameters[contexts].
+ HashTable<String> input_context_ids;
+ for (auto const& context : contexts)
+ input_context_ids.set(context);
+
+ // 5. If input user context ids is not empty and input context ids is not empty, return error with error code
+ // invalid argument.
+ if (!input_user_context_ids.is_empty() && !input_context_ids.is_empty())
+ return WebDriverPromise::rejected(invalid_argument("Parameters 'contexts' and 'userContexts' are mutually exclusive"sv));
+
+ // 6. Let subscription navigables be a set.
+ HashTable<String> subscription_navigables;
+
+ // 7. Let top-level traversable context ids be a set.
+ HashTable<String> top_level_traversable_context_ids;
+
+ // 8. If input context ids is not empty:
+ if (!input_context_ids.is_empty()) {
+ // 1. Let navigables be the result of trying to get valid navigables by ids with input context ids.
+ // 2. Set subscription navigables be get top-level traversables with navigables.
+ // 3. For each navigable in subscription navigables:
+ // 1. Append navigable's navigable id to top-level traversable context ids.
+ // NB: The browser process holds the navigables.
+ auto promise = WebDriverPromise::construct();
+ auto top_level_traversables_promise = m_session.get_bidi_top_level_traversables(move(contexts));
+ promise->add_child(top_level_traversables_promise);
+
+ top_level_traversables_promise->when_resolved([this, promise, event_names = move(event_names), input_user_context_ids = move(input_user_context_ids)](JsonValue& top_level_traversables) mutable {
+ if (!top_level_traversables.is_array() || !all_of(top_level_traversables.as_array().values(), [](auto const& id) { return id.is_string(); })) {
+ promise->reject(invalid_browser_response());
+ return;
+ }
+
+ HashTable<String> subscription_navigables;
+ for (auto const& id : top_level_traversables.as_array().values())
+ subscription_navigables.set(id.as_string());
+
+ auto top_level_traversable_context_ids = subscription_navigables;
+ auto subscribe_promise = complete_subscribe(move(event_names), move(subscription_navigables), move(top_level_traversable_context_ids), move(input_user_context_ids));
+ promise->add_child(subscribe_promise);
+ subscribe_promise->when_resolved([promise](JsonValue& value) { promise->resolve(move(value)); })
+ .when_rejected([promise](auto& error) { promise->reject(move(error)); });
+ })
+ .when_rejected([promise](auto& error) {
+ promise->reject(move(error));
+ });
+ return promise;
+ }
+
+ // 9. Otherwise, if input user context ids is not empty:
+ if (!input_user_context_ids.is_empty()) {
+ // 1. For each user context id of input user context ids:
+ for (auto const& user_context_id : input_user_context_ids) {
+ // 1. Let user context be get user context with user context id.
+ // 2. If user context is null, return error with error code no such user context.
+ if (user_context_id != DEFAULT_USER_CONTEXT_ID)
+ return WebDriverPromise::rejected(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchUserContext, "User context not found"sv));
+
+ // 3. For each top-level traversable in the list of all top-level traversables whose associated user context
+ // is user context:
+ // 1. Append top-level traversable to subscription navigables.
+ for (auto const& traversable : m_session.top_level_traversable_ids())
+ subscription_navigables.set(traversable);
+ }
+ }
+ // 10. Otherwise, set subscription navigables to a set of all top-level traversables in the remote end.
+ else {
+ for (auto const& traversable : m_session.top_level_traversable_ids())
+ subscription_navigables.set(traversable);
+ }
+
+ return complete_subscribe(move(event_names), move(subscription_navigables), move(top_level_traversable_context_ids), move(input_user_context_ids));
+}
+
+NonnullRefPtr<BiDiSession::WebDriverPromise> BiDiSession::complete_subscribe(HashTable<String> event_names, HashTable<String> subscription_navigables, HashTable<String> top_level_traversable_context_ids, HashTable<String> input_user_context_ids)
+{
+ // 11. Let subscription be a subscription with subscription id set to the string representation of a UUID, event
+ // names set to event names, top-level traversable ids set to top-level traversable context ids and user context
+ // ids set to input user context ids.
+ Subscription subscription {
+ .subscription_id = generate_random_uuid(),
+ .event_names = move(event_names),
+ .top_level_traversable_ids = move(top_level_traversable_context_ids),
+ .user_context_ids = move(input_user_context_ids),
+ };
+
+ // 12. Let subscribe step events be a new map.
+ HashMap<String, HashTable<String>> subscribe_step_events;
+
+ // 13. For each event name in the event names:
+ for (auto const& event_name : subscription.event_names) {
+ // 1. If the event with event name event name does not define remote end subscribe steps, continue;
+ if (!subscribe_priority(event_name).has_value())
+ continue;
+
+ // 2. Let existing navigables be a set of top-level traversables for which an event is enabled with session and
+ // event name.
+ auto existing_navigables = set_of_top_level_traversables_for_which_an_event_is_enabled(event_name);
+
+ // 3. Set subscribe step events[event name] to difference of subscription navigables and existing navigables.
+ HashTable<String> navigables;
+ for (auto const& navigable : subscription_navigables) {
+ if (!existing_navigables.contains(navigable))
+ navigables.set(navigable);
+ }
+ subscribe_step_events.set(event_name, move(navigables));
+ }
+
+ // 16. Sort in ascending order subscribe step events using the following less than algorithm given two entries with
+ // keys event name one and event name two:
+ // 1. Let event one be the event with name event name one
+ // 2. Let event two be the event with name event name two
+ // 3. Return true if event one's subscribe priority is less than event two subscribe priority, or false otherwise.
+ Vector<String> sorted_event_names;
+ for (auto const& entry : subscribe_step_events)
+ sorted_event_names.append(entry.key);
+ quick_sort(sorted_event_names, [](auto const& one, auto const& two) {
+ return *subscribe_priority(one) < *subscribe_priority(two);
+ });
+
+ // 17. If subscription is global, let include global be true, otherwise let include global be false.
+ auto include_global = subscription.is_global();
+
+ // 19. Let body be a new map matching the session.SubscribeResult production, with the subscription field set to
+ // subscription's subscription id.
+ JsonObject body;
+ body.set("subscription"sv, subscription.subscription_id);
+
+ // 14. Append subscription to session's subscriptions.
+ // 15. Append subscription's subscription id to session's known subscription ids.
+ m_known_subscription_ids.set(subscription.subscription_id);
+ m_subscriptions.append(move(subscription));
+ update_enabled_events();
+
+ // 18. For each event name → navigables in subscribe step events:
+ // 1. Run the remote end subscribe steps for the event with event name event name given session, navigables and
+ // include global.
+ auto promise = WebDriverPromise::construct();
+ run_subscribe_steps(move(sorted_event_names), move(subscribe_step_events), include_global, promise, move(body));
+
+ // 20. Return success with data body.
+ return promise;
+}
+
+void BiDiSession::run_subscribe_steps(Vector<String> event_names, HashMap<String, HashTable<String>> subscribe_step_events, bool include_global, NonnullRefPtr<WebDriverPromise> promise, JsonValue body)
+{
+ if (event_names.is_empty()) {
+ promise->resolve(move(body));
+ return;
+ }
+
+ auto event_name = event_names.take_first();
+ auto navigables = subscribe_step_events.take(event_name).release_value();
+
+ // NB: WebDriver holds the log event buffer.
+ if (event_name == "log.entryAdded"sv) {
+ run_log_entry_added_subscribe_steps(navigables, include_global);
+ run_subscribe_steps(move(event_names), move(subscribe_step_events), include_global, move(promise), move(body));
+ return;
+ }
+
+ Vector<String> navigable_ids;
+ for (auto const& navigable : navigables)
+ navigable_ids.append(navigable);
+
+ // NB: The browser process runs the subscribe steps, and gives the events they emit.
+ auto steps_promise = m_session.run_bidi_subscribe_steps(event_name, move(navigable_ids));
+ promise->add_child(steps_promise);
+
+ steps_promise->when_resolved([this, event_names = move(event_names), subscribe_step_events = move(subscribe_step_events), include_global, promise, body = move(body)](JsonValue& events) mutable {
+ auto is_valid_event = [&](JsonValue const& event) {
+ if (!event.is_object())
+ return false;
+ auto method = event.as_object().get_string("method"sv);
+ auto params = event.as_object().get("params"sv);
+ return method.has_value() && any_of(s_event_names, [&](auto name) { return name == *method; }) && params.has_value() && params->is_object();
+ };
+ if (!events.is_array() || !all_of(events.as_array().values(), is_valid_event)) {
+ promise->reject(invalid_browser_response());
+ return;
+ }
+
+ for (auto& event : events.as_array().values()) {
+ auto const& event_object = event.as_object();
+ emit_an_event(*event_object.get_string("method"sv), *event_object.get("params"sv));
+ }
+ run_subscribe_steps(move(event_names), move(subscribe_step_events), include_global, promise, move(body));
+ })
+ .when_rejected([promise](auto& error) {
+ promise->reject(move(error));
+ });
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-session-unsubscribe
+NonnullRefPtr<BiDiSession::WebDriverPromise> BiDiSession::session_unsubscribe(JsonValue params_value)
+{
+ // session.UnsubscribeParameters = session.UnsubscribeByAttributesRequest / session.UnsubscribeByIDRequest
+ auto const& params = params_value.as_object();
+
+ // 1. If command parameters does not contain "subscriptions":
+ if (!params.has("subscriptions"sv)) {
+ // NB: The condition implies that command parameters is matching the session.UnsubscribeByAttributesRequest
+ // production.
+ auto events = TRY_OR_REJECT(get_non_empty_list_of_strings(params, "events"sv));
+
+ // 1. Let event names be an empty set.
+ HashTable<String> event_names;
+
+ // 2. For each entry name in command parameters["events"], let event names be the union of event names and the
+ // result of trying to obtain a set of event names with name.
+ for (auto const& name : events) {
+ auto names = TRY_OR_REJECT(obtain_a_set_of_event_names(name));
+ for (auto& event_name : names)
+ event_names.set(move(event_name));
+ }
+
+ // 3. Let new subscriptions to be a list.
+ Vector<Subscription> new_subscriptions;
+
+ // 4. Let matched events to be a set.
+ HashTable<String> matched_events;
+
+ // 5. For each subscription of session's subscriptions:
+ for (auto const& subscription : m_subscriptions) {
+ // 1. If intersection of subscription's event names and event names is an empty set:
+ if (!any_of(event_names, [&](auto const& event_name) { return subscription.event_names.contains(event_name); })) {
+ // 1. append subscription to new subscriptions.
+ new_subscriptions.append(subscription);
+
+ // 2. Continue.
+ continue;
+ }
+
+ // 2. If subscription is not global:
+ if (!subscription.is_global()) {
+ // 1. append subscription to new subscriptions.
+ new_subscriptions.append(subscription);
+
+ // 2. Continue.
+ continue;
+ }
+
+ // 3. Let subscription event names be clone of subscription's event names.
+ auto subscription_event_names = subscription.event_names;
+
+ // 4. For each event name of event names:
+ for (auto const& event_name : event_names) {
+ // 1. If subscription event names contains event name:
+ if (subscription_event_names.contains(event_name)) {
+ // 1. Append event name to matched events.
+ matched_events.set(event_name);
+
+ // 2. Remove event name from subscription event names.
+ subscription_event_names.remove(event_name);
+ }
+ }
+
+ // 5. If subscription event names is not empty:
+ if (!subscription_event_names.is_empty()) {
+ // 1. Let cloned subscription be a subscription with subscription id set to subscription's subscription id,
+ // event names set to a new set containing subscription event names.
+ // 2. append cloned subscription to new subscriptions.
+ new_subscriptions.append({
+ .subscription_id = subscription.subscription_id,
+ .event_names = move(subscription_event_names),
+ .top_level_traversable_ids = {},
+ .user_context_ids = {},
+ });
+ }
+ }
+
+ // 6. If matched events is not equal to event names, return error with error code invalid argument.
+ if (!sets_are_equal(matched_events, event_names))
+ return WebDriverPromise::rejected(invalid_argument("No subscription matches the given events"sv));
+
+ // 7. Set session's subscriptions to new subscriptions.
+ m_subscriptions = move(new_subscriptions);
+ }
+ // 2. Otherwise:
+ else {
+ auto subscription_ids = TRY_OR_REJECT(get_non_empty_list_of_strings(params, "subscriptions"sv));
+
+ // 1. Let subscriptions be create a set with command parameters[subscriptions].
+ HashTable<String> subscriptions;
+ for (auto const& subscription_id : subscription_ids)
+ subscriptions.set(subscription_id);
+
+ // 2. Let unknown subscription ids to difference between subscriptions and session's known subscription ids.
+ // 3. If unknown subscription ids is not empty:
+ // 1. Return error with error code invalid argument.
+ if (any_of(subscriptions, [&](auto const& id) { return !m_known_subscription_ids.contains(id); }))
+ return WebDriverPromise::rejected(invalid_argument("Unknown subscription id"sv));
+
+ // 4. Let subscriptions to remove be an empty set.
+ // 5. For each subscription in session's subscriptions:
+ // 1. If subscriptions contains subscription's subscription id:
+ // 1. Append subscription to subscriptions to remove.
+ // 6. Set session's known subscription ids to difference between session's known subscription ids and
+ // subscriptions.
+ for (auto const& subscription_id : subscriptions)
+ m_known_subscription_ids.remove(subscription_id);
+
+ // 7. Remove each item in subscriptions to remove from session's subscriptions.
+ m_subscriptions.remove_all_matching([&](auto const& subscription) {
+ return subscriptions.contains(subscription.subscription_id);
+ });
+ }
+
+ update_enabled_events();
+
+ // 3. Return success with data null.
+ return WebDriverPromise::resolved(JsonValue {});
+}
+
+}
diff --git a/Services/WebDriver/BiDiSession.h b/Services/WebDriver/BiDiSession.h
new file mode 100644
index 00000000000..44d053099f6
--- /dev/null
+++ b/Services/WebDriver/BiDiSession.h
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/HashTable.h>
+#include <AK/JsonValue.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/String.h>
+#include <AK/Vector.h>
+#include <LibCore/Promise.h>
+#include <LibWebCommon/WebDriver/Error.h>
+#include <WebDriver/WebSocket.h>
+
+namespace WebDriver {
+
+class Session;
+
+// https://w3c.github.io/webdriver-bidi/#bidi-session
+// NB: The state a session has once its BiDi flag is set.
+class BiDiSession {
+ AK_MAKE_NONCOPYABLE(BiDiSession);
+ AK_MAKE_NONMOVABLE(BiDiSession);
+ AK_ALLOC_WITH_KMALLOC;
+
+public:
+ explicit BiDiSession(Session&);
+ ~BiDiSession();
+
+ // https://w3c.github.io/webdriver-bidi/#start-listening-for-a-websocket-connection
+ static ErrorOr<String> start_listening_for_a_websocket_connection(Session const&);
+
+ void did_receive_event(String const& name, JsonValue params, Vector<String> const& top_level_traversable_ids, Vector<String> const& user_context_ids);
+ void did_close_top_level_traversable(String const& id);
+
+ // https://w3c.github.io/webdriver-bidi/#close-the-websocket-connections
+ void close_the_websocket_connections();
+
+private:
+ using WebDriverPromise = Core::Promise<JsonValue, Web::WebDriver::Error>;
+
+ // https://w3c.github.io/webdriver-bidi/#subscription
+ struct Subscription {
+ String subscription_id;
+ HashTable<String> event_names;
+ HashTable<String> top_level_traversable_ids;
+ HashTable<String> user_context_ids;
+
+ // https://w3c.github.io/webdriver-bidi/#subscription-global
+ bool is_global() const { return top_level_traversable_ids.is_empty() && user_context_ids.is_empty(); }
+ };
+
+ static bool accept_connection(WebSocketConnection&, StringView resource_name);
+ void add_connection(NonnullRefPtr<WebSocketConnection>);
+ void handle_a_connection_closing(WebSocketConnection&);
+
+ void handle_an_incoming_message(WebSocketConnection&, WebSocketConnection::MessageType, ByteBuffer data);
+ NonnullRefPtr<WebDriverPromise> run_command(StringView method, JsonValue params);
+
+ void send_an_error_response(WebSocketConnection&, JsonValue command_id, Web::WebDriver::Error const&);
+ void send_a_success_response(WebSocketConnection&, JsonValue command_id, JsonValue result);
+ void emit_an_event(StringView name, JsonValue params);
+
+ bool event_is_enabled(StringView event_name, Vector<String> const& top_level_traversable_ids, Vector<String> const& user_context_ids) const;
+ HashTable<String> set_of_top_level_traversables_for_which_an_event_is_enabled(StringView event_name) const;
+ void update_enabled_events();
+ void remove_destroyed_navigable_from_subscriptions(String const& id);
+ void buffer_a_log_event(Vector<String> const& top_level_traversable_ids, JsonValue event);
+ void run_log_entry_added_subscribe_steps(HashTable<String> const& navigables, bool include_global);
+
+ NonnullRefPtr<WebDriverPromise> session_status();
+ NonnullRefPtr<WebDriverPromise> session_end();
+ NonnullRefPtr<WebDriverPromise> session_subscribe(JsonValue params);
+ NonnullRefPtr<WebDriverPromise> session_unsubscribe(JsonValue params);
+
+ NonnullRefPtr<WebDriverPromise> complete_subscribe(HashTable<String> event_names, HashTable<String> subscription_navigables, HashTable<String> top_level_traversable_context_ids, HashTable<String> input_user_context_ids);
+ void run_subscribe_steps(Vector<String> event_names, HashMap<String, HashTable<String>> subscribe_step_events, bool include_global, NonnullRefPtr<WebDriverPromise>, JsonValue body);
+
+ Session& m_session;
+ bool m_has_ended { false };
+
+ // https://w3c.github.io/webdriver-bidi/#session-websocket-connections
+ Vector<NonnullRefPtr<WebSocketConnection>> m_session_websocket_connections;
+
+ // https://w3c.github.io/webdriver-bidi/#subscriptions
+ Vector<Subscription> m_subscriptions;
+
+ // https://w3c.github.io/webdriver-bidi/#known-subscription-ids
+ HashTable<String> m_known_subscription_ids;
+
+ HashTable<String> m_enabled_events;
+
+ // https://w3c.github.io/webdriver-bidi/#log-event-buffer
+ struct BufferedLogEvent {
+ JsonValue event;
+ size_t size { 0 };
+ };
+ struct BufferedLogEvents {
+ Vector<BufferedLogEvent> events;
+ size_t size { 0 };
+ };
+ HashMap<String, BufferedLogEvents> m_log_event_buffer;
+};
+
+}
diff --git a/Services/WebDriver/BrowserConnection.cpp b/Services/WebDriver/BrowserConnection.cpp
index 97258ea63a0..65b084ed2f0 100644
--- a/Services/WebDriver/BrowserConnection.cpp
+++ b/Services/WebDriver/BrowserConnection.cpp
@@ -39,4 +39,10 @@ void BrowserConnection::command_complete(u64 command_id, Web::WebDriver::Respons
on_command_complete(command_id, move(response));
}
+void BrowserConnection::bidi_event(String name, JsonValue params, Vector<String> top_level_traversable_ids, Vector<String> user_context_ids)
+{
+ if (on_bidi_event)
+ on_bidi_event(move(name), move(params), move(top_level_traversable_ids), move(user_context_ids));
+}
+
}
diff --git a/Services/WebDriver/BrowserConnection.h b/Services/WebDriver/BrowserConnection.h
index 5250fbc9ba0..66a6f96cf97 100644
--- a/Services/WebDriver/BrowserConnection.h
+++ b/Services/WebDriver/BrowserConnection.h
@@ -25,6 +25,7 @@ public:
Function<void(String)> on_did_create_window;
Function<void(String)> on_did_close_window;
Function<void(u64, Web::WebDriver::Response)> on_command_complete;
+ Function<void(String, JsonValue, Vector<String>, Vector<String>)> on_bidi_event;
private:
virtual void die() override;
@@ -32,6 +33,7 @@ private:
virtual void did_create_window(String) override;
virtual void did_close_window(String) override;
virtual void command_complete(u64 command_id, Web::WebDriver::Response) override;
+ virtual void bidi_event(String name, JsonValue params, Vector<String> top_level_traversable_ids, Vector<String> user_context_ids) override;
};
}
diff --git a/Services/WebDriver/CMakeLists.txt b/Services/WebDriver/CMakeLists.txt
index d07e22a2e64..b0443a57b06 100644
--- a/Services/WebDriver/CMakeLists.txt
+++ b/Services/WebDriver/CMakeLists.txt
@@ -1,4 +1,5 @@
set(SOURCES
+ BiDiSession.cpp
BrowserConnection.cpp
Client.cpp
Session.cpp
diff --git a/Services/WebDriver/Session.cpp b/Services/WebDriver/Session.cpp
index 5fde184145d..bd7a3c3458c 100644
--- a/Services/WebDriver/Session.cpp
+++ b/Services/WebDriver/Session.cpp
@@ -164,7 +164,45 @@ ErrorOr<NonnullRefPtr<Session::NewSessionPromise>> Session::create(NonnullRefPtr
// FIXME: 10. Process any extension capabilities in capabilities in an implementation-defined manner.
- // FIXME: 11. Run any WebDriver new session algorithm defined in external specifications, with arguments session, capabilities, and flags.
+ // 11. Run any WebDriver new session algorithm defined in external specifications, with arguments session, capabilities, and flags.
+ // https://w3c.github.io/webdriver-bidi/#establishing
+ [&] {
+ // 1. If flags contains "bidi", return.
+ // NB: We do not support BiDi-only sessions, so flags never contains "bidi".
+ // 2. Let webSocketUrl be the result of getting a property named "webSocketUrl" from capabilities.
+ auto web_socket_url = capabilities.get("webSocketUrl"sv);
+
+ // 3. If webSocketUrl is undefined, return.
+ if (!web_socket_url.has_value())
+ return;
+
+ // 4. Assert: webSocketUrl is true.
+ VERIFY(web_socket_url->is_bool() && web_socket_url->as_bool());
+
+ // 5. Let listener be the result of start listening for a WebSocket connection given session.
+ // 6. Set webSocketUrl to the result of construct a WebSocket URL with listener and session.
+ auto url = BiDiSession::start_listening_for_a_websocket_connection(*session);
+ if (url.is_error()) {
+ warnln("Unable to listen for WebSocket connections: {}", url.error());
+ return;
+ }
+
+ // 7. Set a property on capabilities named "webSocketUrl" to webSocketUrl.
+ capabilities.set("webSocketUrl"sv, url.release_value());
+
+ // 8. Set session's BiDi flag to true.
+ session->m_bidi_session = make<BiDiSession>(*session);
+
+ // 9. Append "bidi" to flags.
+ // NB: The flags are not used after the session is created, and its BiDi session marks it as a BiDi session.
+ }();
+
+ // NB: A session that requested a WebSocket URL but could not listen for one is not created.
+ if (capabilities.has("webSocketUrl"sv) && !session->m_bidi_session) {
+ session->close();
+ state->promise->reject(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::SessionNotCreated, "Unable to listen for WebSocket connections"sv));
+ return;
+ }
// 12. Append session to active sessions.
s_sessions.set(session->session_id(), session);
@@ -351,6 +389,11 @@ void Session::close()
// 2. Remove session from active sessions.
s_sessions.remove(m_session_id);
+ // https://w3c.github.io/webdriver-bidi/#cleanup-the-session
+ // 1. Close the WebSocket connections with session.
+ if (m_bidi_session)
+ m_bidi_session->close_the_websocket_connections();
+
// 3. Perform the following substeps based on the remote end's type:
// -> Remote end is an endpoint node
// 1. If the list of active sessions is empty:
@@ -386,6 +429,7 @@ void Session::close()
m_browser_connection->on_did_create_window = nullptr;
m_browser_connection->on_did_close_window = nullptr;
m_browser_connection->on_command_complete = nullptr;
+ m_browser_connection->on_bidi_event = nullptr;
m_browser_connection->async_close_session();
m_browser_connection = nullptr;
}
@@ -452,6 +496,11 @@ ErrorOr<void> Session::accept_browser_transport(NonnullOwnPtr<IPC::Transport> tr
promise.value()->resolve(response.release_value());
};
+ browser_connection->on_bidi_event = [this](String name, JsonValue params, Vector<String> top_level_traversable_ids, Vector<String> user_context_ids) {
+ if (m_bidi_session)
+ m_bidi_session->did_receive_event(name, move(params), top_level_traversable_ids, user_context_ids);
+ };
+
m_browser_connection = move(browser_connection);
#if defined(AK_OS_MACOS)
m_browser_mach_port_server = nullptr;
@@ -601,6 +650,9 @@ void Session::remove_window(StringView window_handle)
if (!m_windows.remove(window_handle))
return;
+ if (m_bidi_session)
+ m_bidi_session->did_close_top_level_traversable(MUST(String::from_utf8(window_handle)));
+
if (m_current_window_handle == window_handle)
m_current_window_handle = "NoSuchWindowPleaseSelectANewOne"_string;
@@ -833,6 +885,49 @@ void Session::remove_window_handle_became_available_callback(String const& handl
m_window_handle_became_available_callbacks.remove(callbacks);
}
+bool Session::is_active() const
+{
+ return s_sessions.contains(m_session_id);
+}
+
+Vector<String> Session::top_level_traversable_ids() const
+{
+ // https://w3c.github.io/webdriver-bidi/#type-browsingContext-Browsingcontext
+ // For navigables with an associated WebDriver window handle the navigable id must be the same as the window handle.
+ Vector<String> ids;
+ ids.ensure_capacity(m_windows.size());
+ for (auto const& window_handle : m_windows.keys())
+ ids.unchecked_append(window_handle);
+ return ids;
+}
+
+NonnullRefPtr<Session::WebDriverPromise> Session::perform_bidi_browser_command(StringView method, JsonValue params)
+{
+ return perform_browser_command([this, method = MUST(String::from_utf8(method)), params = move(params)](u64 command_id) mutable {
+ m_browser_connection->async_bidi_command(command_id, move(method), move(params));
+ });
+}
+
+NonnullRefPtr<Session::WebDriverPromise> Session::get_bidi_top_level_traversables(Vector<String> navigable_ids)
+{
+ return perform_browser_command([this, navigable_ids = move(navigable_ids)](u64 command_id) mutable {
+ m_browser_connection->async_bidi_get_top_level_traversables(command_id, move(navigable_ids));
+ });
+}
+
+NonnullRefPtr<Session::WebDriverPromise> Session::run_bidi_subscribe_steps(String const& event_name, Vector<String> top_level_traversable_ids)
+{
+ return perform_browser_command([this, event_name, top_level_traversable_ids = move(top_level_traversable_ids)](u64 command_id) mutable {
+ m_browser_connection->async_bidi_run_subscribe_steps(command_id, event_name, move(top_level_traversable_ids));
+ });
+}
+
+void Session::set_bidi_enabled_events(Vector<String> event_names)
+{
+ if (m_browser_connection)
+ m_browser_connection->async_set_bidi_enabled_events(move(event_names));
+}
+
ErrorOr<void, Web::WebDriver::Error> Session::ensure_current_window_handle_is_valid() const
{
if (!m_windows.contains(m_current_window_handle))
diff --git a/Services/WebDriver/Session.h b/Services/WebDriver/Session.h
index 017933c4c0c..f0c36371b28 100644
--- a/Services/WebDriver/Session.h
+++ b/Services/WebDriver/Session.h
@@ -32,6 +32,7 @@
#include <LibWebCommon/WebDriver/Response.h>
#include <LibWebCommon/WebDriver/SessionBrowsingContext.h>
#include <LibWebCommon/WebDriver/TimeoutsConfiguration.h>
+#include <WebDriver/BiDiSession.h>
#include <WebDriver/BrowserConnection.h>
#include <WebDriver/Client.h>
@@ -101,6 +102,19 @@ public:
NonnullRefPtr<WebDriverPromise> run_top_level_content_command(StringView name, JsonValue payload = {}, Vector<String> arguments = {});
ErrorOr<void, Web::WebDriver::Error> ensure_current_window_handle_is_valid() const;
+ // https://w3c.github.io/webdriver-bidi/#bidi-flag
+ BiDiSession* bidi_session() { return m_bidi_session.ptr(); }
+
+ // https://w3c.github.io/webdriver/#dfn-active-session
+ bool is_active() const;
+
+ Vector<String> top_level_traversable_ids() const;
+
+ NonnullRefPtr<WebDriverPromise> perform_bidi_browser_command(StringView method, JsonValue params);
+ NonnullRefPtr<WebDriverPromise> get_bidi_top_level_traversables(Vector<String> navigable_ids);
+ NonnullRefPtr<WebDriverPromise> run_bidi_subscribe_steps(String const& event_name, Vector<String> top_level_traversable_ids);
+ void set_bidi_enabled_events(Vector<String> event_names);
+
private:
Session(NonnullRefPtr<Client> client, JsonObject const& capabilities, String session_id, Web::WebDriver::SessionFlags flags);
@@ -135,6 +149,8 @@ private:
RefPtr<BrowserConnection> m_browser_connection;
bool m_closing { false };
+ OwnPtr<BiDiSession> m_bidi_session;
+
u64 m_next_browser_command_id { 1 };
HashMap<u64, NonnullRefPtr<WebDriverPromise>> m_pending_browser_commands;
RefPtr<ServerPromise> m_start_promise;
diff --git a/Services/WebDriver/WebDriverBrowserClient.ipc b/Services/WebDriver/WebDriverBrowserClient.ipc
index 46cb3898aa3..d606b906d6e 100644
--- a/Services/WebDriver/WebDriverBrowserClient.ipc
+++ b/Services/WebDriver/WebDriverBrowserClient.ipc
@@ -20,4 +20,10 @@ endpoint WebDriverBrowserClient {
set_page_load_strategy(Web::WebDriver::PageLoadStrategy page_load_strategy) =|
set_strict_file_interactability(bool strict_file_interactability) =|
set_timeouts_configuration(JsonValue timeouts) =|
+
+ // https://w3c.github.io/webdriver-bidi/
+ bidi_command(u64 command_id, String method, JsonValue params) =|
+ bidi_get_top_level_traversables(u64 command_id, Vector<String> navigable_ids) =|
+ bidi_run_subscribe_steps(u64 command_id, String event_name, Vector<String> top_level_traversable_ids) =|
+ set_bidi_enabled_events(Vector<String> event_names) =|
}
diff --git a/Services/WebDriver/WebDriverBrowserServer.ipc b/Services/WebDriver/WebDriverBrowserServer.ipc
index 6d9128870c1..c79c2d259d5 100644
--- a/Services/WebDriver/WebDriverBrowserServer.ipc
+++ b/Services/WebDriver/WebDriverBrowserServer.ipc
@@ -4,4 +4,7 @@ endpoint WebDriverBrowserServer {
did_create_window(String handle) =|
did_close_window(String handle) =|
command_complete(u64 command_id, Web::WebDriver::Response response) =|
+
+ // https://w3c.github.io/webdriver-bidi/#events
+ bidi_event(String name, JsonValue params, Vector<String> top_level_traversable_ids, Vector<String> user_context_ids) =|
}
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index a7b6f7dc7fd..c65d0e228da 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -42,11 +42,13 @@ if (LINUX)
endif()
if (APPLE AND NOT IOS)
- ladybird_test(TestWebDriverMachBootstrap.cpp LibWebView LIBS LibGfx LibIPC LibURL LibWebCommon OpenSSL::Crypto OpenSSL::SSL)
+ ladybird_test(TestWebDriverMachBootstrap.cpp LibWebView LIBS LibGfx LibIPC LibURL LibWebCommon LibWebSocket OpenSSL::Crypto OpenSSL::SSL)
target_sources(TestWebDriverMachBootstrap PRIVATE
+ "${LADYBIRD_SOURCE_DIR}/Services/WebDriver/BiDiSession.cpp"
"${LADYBIRD_SOURCE_DIR}/Services/WebDriver/BrowserConnection.cpp"
"${LADYBIRD_SOURCE_DIR}/Services/WebDriver/Client.cpp"
"${LADYBIRD_SOURCE_DIR}/Services/WebDriver/Session.cpp"
+ "${LADYBIRD_SOURCE_DIR}/Services/WebDriver/WebSocket.cpp"
)
target_include_directories(TestWebDriverMachBootstrap PRIVATE "${LADYBIRD_SOURCE_DIR}/Services" "${CMAKE_BINARY_DIR}/Services")
set_tests_properties(TestWebDriverMachBootstrap PROPERTIES TIMEOUT 30)
@@ -398,6 +400,17 @@ if (BUILD_TESTING AND NOT WIN32)
)
set_tests_properties(TestWebDriverForceDark PROPERTIES TIMEOUT 120)
+ add_test(
+ NAME TestWebDriverBiDi
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-webdriver-bidi.py $<TARGET_FILE:WebDriver>
+ )
+ set_tests_properties(TestWebDriverBiDi PROPERTIES TIMEOUT 120)
+ add_test(
+ NAME TestWebDriverBiDiCleanup
+ COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-webdriver-bidi-cleanup.py
+ )
+ set_tests_properties(TestWebDriverBiDiCleanup PROPERTIES TIMEOUT 30)
+
add_test(
NAME TestWebDriverErrorKeepAlive
COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test-webdriver-error-keep-alive.py $<TARGET_FILE:WebDriver>
diff --git a/Tests/LibWebView/TestCrashOverlay.cpp b/Tests/LibWebView/TestCrashOverlay.cpp
index aea5d8e149b..e551800ab75 100644
--- a/Tests/LibWebView/TestCrashOverlay.cpp
+++ b/Tests/LibWebView/TestCrashOverlay.cpp
@@ -8,6 +8,7 @@
#include <AK/Random.h>
#include <AK/ScopeGuard.h>
#include <AK/String.h>
+#include <LibCore/ArgsParser.h>
#include <LibCore/Directory.h>
#include <LibCore/EventLoop.h>
#include <LibCore/StandardPaths.h>
@@ -16,6 +17,7 @@
#include <LibMain/Main.h>
#include <LibURL/Parser.h>
#include <LibWebView/Application.h>
+#include <LibWebView/CanonicalDocument.h>
#include <LibWebView/HeadlessWebView.h>
#include <LibWebView/Utilities.h>
#include <stdlib.h>
@@ -38,7 +40,16 @@ public:
web_content_options.is_test_mode = WebView::IsTestMode::Yes;
}
+ virtual void create_platform_arguments(Core::ArgsParser& parser) override
+ {
+ parser.add_option(m_bidi_reload_only, "Run only the BiDi reload crash recovery case", "bidi-reload-only");
+ }
+
+ bool bidi_reload_only() const { return m_bidi_reload_only; }
virtual bool should_coordinate_browser_process() const override { return false; }
+
+private:
+ bool m_bidi_reload_only { false };
};
}
@@ -49,6 +60,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
TRY(Core::Directory::create(test_directory, Core::Directory::CreateDirectories::Yes));
ScopeGuard cleanup = [&] { MUST(FileSystem::remove(test_directory, FileSystem::RecursionMode::Allowed)); };
VERIFY(setenv("XDG_CONFIG_HOME", test_directory.characters(), 1) == 0);
+ VERIFY(setenv("XDG_DATA_HOME", test_directory.characters(), 1) == 0);
#if defined(LADYBIRD_BINARY_PATH)
auto app = TRY(TestApplication::create(arguments, LADYBIRD_BINARY_PATH));
#else
@@ -90,6 +102,42 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
VERIFY(view->crash_overlay_failed_url() == failed_url.serialize());
};
+ auto const& session_history = view->traversable().session_history();
+ auto crash_and_load = [&](auto load) {
+ Core::EventLoop::current().spin_until([&] { return !view->crash_overlay_active(); });
+ view->debug_request("crash-current-page"sv);
+ Core::EventLoop::current().spin_until([&] { return view->crash_overlay_active(); });
+ auto loads_before = loads_finished;
+ load();
+ Core::EventLoop::current().spin_until([&] { return loads_finished > loads_before; });
+ };
+
+ auto check_bidi_reload = [&] {
+ // A BiDi reload recovers the active document with its command's navigation ID, and dismisses the crash screen
+ // once the replacement document paints.
+ auto document_before_crash = view->traversable().active_document().id();
+ // NB: The callback is cleared below before its captured state leaves scope.
+ IGNORE_USE_IN_ESCAPING_LAMBDA bool recovered_document_painted = false;
+ view->on_ready_to_paint = [view = view->make_weak_ptr(), document_before_crash, &recovered_document_painted] {
+ if (view && view->traversable().active_document().id() != document_before_crash)
+ recovered_document_painted = true;
+ };
+ auto navigation_id = Utf16String::from_utf8(generate_random_uuid());
+ crash_and_load([view = view.ptr(), navigation_id] { view->reload_for_webdriver_bidi(WebView::BypassCache::No, navigation_id); });
+ Core::EventLoop::current().spin_until([&] { return recovered_document_painted; });
+ VERIFY(!view->crash_overlay_active());
+ view->on_ready_to_paint = nullptr;
+ };
+
+ if (app->bidi_reload_only()) {
+ check_bidi_reload();
+ VERIFY(view->url() == failed_url);
+ VERIFY(evaluate("document.body.textContent === 'original-page-content'"sv).as_bool());
+ VERIFY(session_history.used_step_count() == 2);
+ outln("PASS: BiDi reload recovers the crash overlay");
+ return 0;
+ }
+
crash_and_wait_for_screen();
view->reload();
Core::EventLoop::current().spin_until([&] { return loads_finished >= 4; });
@@ -112,15 +160,6 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
// A load from the browser's UI navigates the tab whose document was lost as it would the document: to its URL, it
// replaces its entry, to another it pushes one, and to a fragment of its URL it loads the URL again.
- auto const& session_history = view->traversable().session_history();
- auto crash_and_load = [&](auto load) {
- Core::EventLoop::current().spin_until([&] { return !view->crash_overlay_active(); });
- view->debug_request("crash-current-page"sv);
- Core::EventLoop::current().spin_until([&] { return view->crash_overlay_active(); });
- auto loads_before = loads_finished;
- load();
- Core::EventLoop::current().spin_until([&] { return loads_finished > loads_before; });
- };
crash_and_load([&] { view->load(failed_url); });
VERIFY(session_history.current_step() == history_step);
VERIFY(session_history.used_step_count() == 2);
@@ -140,6 +179,10 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
crash_and_load([&] { view->load_html("<title>HTML</title>loaded-html"sv); });
VERIFY(session_history.used_step_count() == 5);
VERIFY(evaluate("document.body.textContent === 'loaded-html'"sv).as_bool());
+
+ check_bidi_reload();
+ VERIFY(evaluate("document.body.textContent === 'loaded-html'"sv).as_bool());
+ VERIFY(session_history.used_step_count() == 5);
outln("PASS: native crash overlay state, reload and history");
return 0;
}
diff --git a/Tests/LibWebView/test-webdriver-bidi-cleanup.py b/Tests/LibWebView/test-webdriver-bidi-cleanup.py
new file mode 100755
index 00000000000..ad111346a66
--- /dev/null
+++ b/Tests/LibWebView/test-webdriver-bidi-cleanup.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+#
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+import importlib
+import subprocess
+import sys
+import unittest
+
+from unittest.mock import Mock
+from unittest.mock import patch
+
+bidi_helpers = importlib.import_module("test-webdriver-bidi")
+
+
+class CleanupTests(unittest.TestCase):
+ def resources(self):
+ server, driver, connection, bidi = Mock(), Mock(), Mock(), Mock()
+ driver.wait.side_effect = [subprocess.TimeoutExpired("WebDriver", 5), 0]
+ server.shutdown.side_effect = OSError("server shutdown failed")
+ bidi.close.side_effect = OSError("WebSocket close failed")
+ connection.close.side_effect = OSError("HTTP close failed")
+ return server, driver, connection, bidi
+
+ def assert_cleaned(self, server, driver, connection, bidi):
+ server.release_response.set.assert_called_once()
+ bidi.close.assert_called_once()
+ connection.close.assert_called_once()
+ driver.terminate.assert_called_once()
+ driver.kill.assert_called_once()
+ self.assertEqual(driver.wait.call_count, 2)
+ server.shutdown.assert_called_once()
+ server.server_close.assert_called_once()
+
+ def test_cleanup_failures_preserve_primary_error_and_release_every_resource(self):
+ resources = self.resources()
+ primary = AssertionError("original test failure")
+ with patch.object(bidi_helpers.helpers, "request", side_effect=OSError("DELETE failed")) as delete:
+ with self.assertRaises(AssertionError) as raised:
+ try:
+ raise primary
+ finally:
+ bidi_helpers.cleanup_resources(*resources, "session", primary_error=sys.exc_info()[1])
+ self.assertIs(raised.exception, primary)
+ delete.assert_called_once()
+ self.assert_cleaned(*resources)
+
+ def test_cleanup_without_primary_error_reports_failure_after_releasing_resources(self):
+ resources = self.resources()
+ failure = OSError("DELETE failed")
+ with patch.object(bidi_helpers.helpers, "request", side_effect=failure):
+ with self.assertRaises(OSError) as raised:
+ bidi_helpers.cleanup_resources(*resources, "session")
+ self.assertIs(raised.exception, failure)
+ self.assert_cleaned(*resources)
+
+ def test_termination_failure_still_waits_and_kills(self):
+ resources = self.resources()
+ resources[1].terminate.side_effect = OSError("terminate failed")
+ with patch.object(bidi_helpers.helpers, "request", side_effect=OSError("DELETE failed")):
+ bidi_helpers.cleanup_resources(*resources, "session", primary_error=AssertionError("primary"))
+ self.assert_cleaned(*resources)
+
+ def test_unexpected_wait_failure_still_kills_and_waits(self):
+ resources = self.resources()
+ resources[1].wait.side_effect = [OSError("wait failed"), 0]
+ with patch.object(bidi_helpers.helpers, "request", side_effect=OSError("DELETE failed")):
+ bidi_helpers.cleanup_resources(*resources, "session", primary_error=AssertionError("primary"))
+ self.assert_cleaned(*resources)
+
+ def test_reader_close_failure_does_not_skip_socket_close(self):
+ connection = object.__new__(bidi_helpers.BiDiConnection)
+ connection.reader = Mock()
+ connection.socket = Mock()
+ connection.reader.close.side_effect = OSError("reader close failed")
+ with self.assertRaises(OSError):
+ connection.close()
+ connection.socket.close.assert_called_once()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.py
new file mode 100755
index 00000000000..d79ced0bfe6
--- /dev/null
+++ b/Tests/LibWebView/test-webdriver-bidi.py
@@ -0,0 +1,494 @@
+#!/usr/bin/env python3
+#
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+import argparse
+import base64
+import hashlib
+import http.client
+import http.server
+import importlib
+import json
+import os
+import socket
+import struct
+import subprocess
+import sys
+import tempfile
+import threading
+import urllib.parse
+
+helpers = importlib.import_module("test-webdriver-error-keep-alive")
+
+
+class BiDiConnection:
+ def __init__(self, url, *, host=None, origin=None, expected_status=101):
+ url = urllib.parse.urlsplit(url)
+ hostname, port = url.hostname, url.port
+ if hostname is None or port is None:
+ raise ValueError("The WebSocket URL must contain a hostname and port")
+ self.socket = socket.create_connection((hostname, port), timeout=30)
+ self.reader = self.socket.makefile("rb")
+ key = base64.b64encode(os.urandom(16)).decode()
+ host = host or f"{hostname}:{port}"
+ origin_header = f"Origin: {origin}\r\n" if origin else ""
+ self.socket.sendall(
+ (
+ f"GET {url.path} HTTP/1.1\r\nHost: {host}\r\n"
+ f"Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n"
+ f"Sec-WebSocket-Version: 13\r\n{origin_header}\r\n"
+ ).encode()
+ )
+ assert int(self.reader.readline().split()[1]) == expected_status
+ headers = {}
+ while (line := self.reader.readline()) != b"\r\n":
+ name, value = line.decode().split(":", 1)
+ headers[name.lower()] = value.strip()
+ if expected_status != 101:
+ return
+ expected_accept = base64.b64encode(
+ hashlib.sha1((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()).digest()
+ )
+ assert headers["sec-websocket-accept"].encode() == expected_accept
+ self.next_id = 0
+ self.responses = {}
+ self.events = []
+
+ def close(self):
+ try:
+ self.reader.close()
+ finally:
+ self.socket.close()
+
+ def send(self, method, params):
+ self.next_id += 1
+ payload = json.dumps({"id": self.next_id, "method": method, "params": params}).encode()
+ mask = os.urandom(4)
+ if len(payload) < 126:
+ header = bytes([0x81, 0x80 | len(payload)])
+ else:
+ header = bytes([0x81, 0x80 | 126]) + struct.pack("!H", len(payload))
+ self.socket.sendall(header + mask + bytes(byte ^ mask[index % 4] for index, byte in enumerate(payload)))
+ return self.next_id
+
+ def read_message(self):
+ first, second = self.reader.read(2)
+ assert first == 0x81, f"Unexpected WebSocket frame: {first:#x}"
+ assert not second & 0x80
+ length = second & 0x7F
+ if length == 126:
+ length = struct.unpack("!H", self.reader.read(2))[0]
+ elif length == 127:
+ length = struct.unpack("!Q", self.reader.read(8))[0]
+ message = json.loads(self.reader.read(length))
+ if "id" in message:
+ self.responses[message["id"]] = message
+ else:
+ self.events.append(message)
+
+ def response(self, command_id):
+ while command_id not in self.responses:
+ self.read_message()
+ return self.responses.pop(command_id)
+
+ def event(self, method):
+ while True:
+ for index, event in enumerate(self.events):
+ if event["method"] == method:
+ return self.events.pop(index)["params"]
+ self.read_message()
+
+ def command(self, method, params):
+ response = self.response(self.send(method, params))
+ assert response["type"] == "success", response
+ return response["result"]
+
+ def evaluate(self, context, expression, **options):
+ return self.command(
+ "script.evaluate",
+ {"target": {"context": context}, "expression": expression, "awaitPromise": False, **options},
+ )
+
+
+class ReloadServer(http.server.ThreadingHTTPServer):
+ daemon_threads = True
+
+ def __init__(self):
+ super().__init__(("127.0.0.1", 0), ReloadHandler)
+ self.block_reload: bool = False
+ self.request_received: threading.Event = threading.Event()
+ self.release_response: threading.Event = threading.Event()
+
+
+class ReloadHandler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ server = self.server
+ assert isinstance(server, ReloadServer)
+ if server.block_reload:
+ server.request_received.set()
+ if not server.release_response.wait(30):
+ raise TimeoutError("The test did not release the reload response")
+ body = b"<!doctype html><title>Reload target</title>"
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ try:
+ self.wfile.write(body)
+ except BrokenPipeError:
+ pass
+
+ def log_message(self, format, *args):
+ pass
+
+
+def check_viewport_changes(bidi, connection, session_id, first, second):
+ def metrics(context):
+ result = bidi.evaluate(context, "[innerWidth, innerHeight, devicePixelRatio]")
+ return [item["value"] for item in result["result"]["value"]]
+
+ bidi.command(
+ "browsingContext.setViewport",
+ {"context": first, "viewport": {"width": 320, "height": 200}, "devicePixelRatio": 1},
+ )
+ bidi.command(
+ "browsingContext.setViewport",
+ {"context": second, "viewport": {"width": 320, "height": 200}, "devicePixelRatio": 2},
+ )
+ # Keep the requested CSS size across fractional device ratios, including after a failed batch.
+ bidi.command(
+ "browsingContext.setViewport",
+ {"context": first, "viewport": {"width": 333, "height": 201}, "devicePixelRatio": 1.5},
+ )
+ assert metrics(first) == [333, 201, 1.5], metrics(first)
+ bidi.command("browsingContext.setViewport", {"context": first, "devicePixelRatio": 0.5})
+ before = [metrics(first), metrics(second)]
+ result = bidi.response(
+ bidi.send(
+ "browsingContext.setViewport", {"userContexts": ["default"], "viewport": {"width": 9000, "height": 1}}
+ )
+ )
+ assert result["type"] == "error" and result["error"] == "unsupported operation", result
+ after = [metrics(first), metrics(second)]
+ assert after == before, f"Failed viewport command changed targets: before={before}, after={after}"
+
+ bidi.command("browsingContext.setViewport", {"context": first, "devicePixelRatio": 2})
+ assert metrics(first) == [333, 201, 2], metrics(first)
+ bidi.command("browsingContext.setViewport", {"context": first, "devicePixelRatio": 1.25})
+ assert metrics(first) == [333, 201, 1.25], metrics(first)
+ # Integer device pixels quantize this viewport at DPR < 1; retain its exact requested CSS size anyway.
+ bidi.command("browsingContext.setViewport", {"context": first, "devicePixelRatio": 0.5})
+ assert metrics(first) == [334, 202, 0.5], metrics(first)
+ bidi.command("browsingContext.setViewport", {"context": first, "devicePixelRatio": 2})
+ assert metrics(first) == [333, 201, 2], metrics(first)
+
+ # A rejected first override must not capture the defaults used by a later successful override.
+ fresh = bidi.command("browsingContext.create", {"type": "window"})["context"]
+ result = bidi.response(
+ bidi.send(
+ "browsingContext.setViewport",
+ {"context": fresh, "viewport": {"width": 16385, "height": 1}, "devicePixelRatio": 1},
+ )
+ )
+ assert result["type"] == "error" and result["error"] == "unsupported operation", result
+ status, payload, _ = helpers.request(connection, "POST", f"/session/{session_id}/window", {"handle": fresh})
+ assert status == 200, payload
+ status, payload, _ = helpers.request(
+ connection, "POST", f"/session/{session_id}/window/rect", {"width": 640, "height": 480}
+ )
+ assert status == 200, payload
+ expected_default = metrics(fresh)
+ assert expected_default[:2] == [640, 480], expected_default
+ bidi.command(
+ "browsingContext.setViewport",
+ {"context": fresh, "viewport": {"width": 200, "height": 100}, "devicePixelRatio": 1},
+ )
+ bidi.command("browsingContext.setViewport", {"context": fresh, "viewport": None, "devicePixelRatio": None})
+ restored = metrics(fresh)
+ assert restored == expected_default, (
+ f"Failed command captured stale defaults: expected={expected_default}, actual={restored}"
+ )
+ # A classic window resize supersedes the CSS size from the previous BiDi override.
+ bidi.command(
+ "browsingContext.setViewport",
+ {"context": fresh, "viewport": {"width": 333, "height": 201}, "devicePixelRatio": 1.5},
+ )
+ status, payload, _ = helpers.request(
+ connection, "POST", f"/session/{session_id}/window/rect", {"width": 600, "height": 450}
+ )
+ assert status == 200, payload
+ assert metrics(fresh) == [400, 300, 1.5], metrics(fresh)
+ bidi.command("browsingContext.setViewport", {"context": fresh, "devicePixelRatio": 2})
+ assert metrics(fresh) == [400, 300, 2], metrics(fresh)
+ bidi.command("browsingContext.setViewport", {"context": fresh, "viewport": None, "devicePixelRatio": None})
+ assert metrics(fresh) == expected_default, metrics(fresh)
+ helpers.request(connection, "POST", f"/session/{session_id}/window", {"handle": first})
+ bidi.command("browsingContext.close", {"context": fresh})
+ for context in [first, second]:
+ bidi.command("browsingContext.setViewport", {"context": context, "viewport": None, "devicePixelRatio": None})
+
+
+def cleanup_resources(server, webdriver, connection, bidi, session_id, *, primary_error=None):
+ errors = []
+
+ def attempt(action):
+ try:
+ action()
+ except BaseException as error:
+ errors.append(error)
+
+ def stop_driver():
+ if webdriver is None:
+ return
+ attempt(webdriver.terminate)
+ try:
+ webdriver.wait(timeout=5)
+ except BaseException as error:
+ if not isinstance(error, subprocess.TimeoutExpired):
+ errors.append(error)
+ attempt(webdriver.kill)
+ attempt(lambda: webdriver.wait(timeout=5))
+
+ attempt(server.release_response.set)
+ if session_id and connection:
+ attempt(lambda: helpers.request(connection, "DELETE", f"/session/{session_id}"))
+ if bidi:
+ attempt(bidi.close)
+ if connection:
+ attempt(connection.close)
+ attempt(stop_driver)
+ attempt(server.shutdown)
+ attempt(server.server_close)
+ if errors and primary_error is None:
+ raise errors[0]
+
+
+def run_test(webdriver_binary):
+ with tempfile.TemporaryDirectory(prefix="ladybird-webdriver-bidi-") as profile:
+ server = ReloadServer()
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ port = helpers.unused_port()
+ webdriver = None
+ connection = None
+ bidi = None
+ session_id = None
+ try:
+ webdriver = subprocess.Popen(
+ [
+ webdriver_binary,
+ "--headless",
+ "--expose-internals-object",
+ f"--profile-path={profile}",
+ "-l",
+ "127.0.0.1",
+ "-p",
+ str(port),
+ ]
+ )
+ helpers.wait_for_port(port)
+ connection = http.client.HTTPConnection("127.0.0.1", port, timeout=30)
+ status, payload, _ = helpers.request(
+ connection,
+ "POST",
+ "/session",
+ {"capabilities": {"alwaysMatch": {"webSocketUrl": True}}},
+ )
+ assert status == 200, payload
+ session_id = payload["value"]["sessionId"]
+ websocket_url = payload["value"]["capabilities"]["webSocketUrl"]
+ # The transport is reusable; WebDriver still owns the loopback Host, Origin and session-path policy.
+ for policy in [
+ {"host": f"example.test:{urllib.parse.urlsplit(websocket_url).port}"},
+ {"origin": "https://example.test"},
+ ]:
+ rejected = BiDiConnection(websocket_url, expected_status=403, **policy)
+ rejected.close()
+ unknown_session_url = websocket_url.rsplit("/", 1)[0] + "/00000000-0000-4000-8000-000000000000"
+ rejected = BiDiConnection(unknown_session_url, expected_status=404)
+ rejected.close()
+ bidi = BiDiConnection(websocket_url)
+ context = bidi.command("browsingContext.getTree", {})["contexts"][0]["context"]
+
+ bidi.command("browsingContext.getTree", {"maxDepth": 1.0})
+ for depth in [-1, 0.5, float(2**53)]:
+ result = bidi.response(bidi.send("browsingContext.getTree", {"maxDepth": depth}))
+ assert result["type"] == "error" and result["error"] == "invalid argument", result
+
+ # Object classification uses the engine's public embedding API.
+ values = {
+ "new WeakMap()": "weakmap",
+ "new WeakSet()": "weakset",
+ "(function*() {})()": "generator",
+ "(async function*() {})()": "generator",
+ "new Proxy({}, {})": "proxy",
+ "new ArrayBuffer(8)": "arraybuffer",
+ "new Map([[1, 2]])": "map",
+ "new Set([1, 2])": "set",
+ }
+ for expression, expected_type in values.items():
+ result = bidi.evaluate(context, expression)
+ assert result["type"] == "success", result
+ assert result["result"]["type"] == expected_type, result
+
+ # Deserialization creates values in the selected environment and wraps shared nodes there.
+ node = bidi.evaluate(context, "document.body")["result"]
+ result = bidi.command(
+ "script.callFunction",
+ {
+ "target": {"context": context},
+ "functionDeclaration": "(array, date, map, set, object, node) => [array[0], date.getUTCFullYear(), map.get(1), set.has(2), object.k, node === document.body]",
+ "awaitPromise": False,
+ "arguments": [
+ {"type": "array", "value": [{"type": "number", "value": 7}]},
+ {"type": "date", "value": "2026-01-01T00:00:00.000Z"},
+ {"type": "map", "value": [[{"type": "number", "value": 1}, {"type": "number", "value": 2}]]},
+ {"type": "set", "value": [{"type": "number", "value": 2}]},
+ {"type": "object", "value": [["k", {"type": "number", "value": 9}]]},
+ {"sharedId": node["sharedId"]},
+ ],
+ },
+ )
+ assert [value["value"] for value in result["result"]["value"]] == [7, 2026, 2, True, 9, True], result
+ environment = bidi.command("script.getRealms", {"context": context})["realms"][0]["realm"]
+ result = bidi.command(
+ "script.evaluate", {"target": {"realm": environment}, "expression": "42", "awaitPromise": False}
+ )
+ assert result["result"]["value"] == 42, result
+
+ bidi.command("session.subscribe", {"events": ["script.message", "log.entryAdded"]})
+ bidi.command(
+ "script.callFunction",
+ {
+ "target": {"context": context},
+ "functionDeclaration": "channel => { channel(17); }",
+ "awaitPromise": False,
+ "arguments": [{"type": "channel", "value": {"channel": "test"}}],
+ },
+ )
+ message = bidi.event("script.message")
+ assert message["channel"] == "test" and message["data"]["value"] == 17, message
+ bidi.evaluate(context, "console.log('BiDi test')")
+ message = bidi.event("log.entryAdded")
+ assert message["text"] == "BiDi test" and message["source"]["realm"] == environment, message
+
+ # The pending response must survive collection even if script keeps no reference to its promise.
+ pending = bidi.send(
+ "script.evaluate",
+ {"target": {"context": context}, "expression": "new Promise(() => {})", "awaitPromise": True},
+ )
+ bidi.evaluate(context, "internals.gc(); undefined")
+ assert pending not in bidi.responses, bidi.responses
+
+ # Another awaited promise settles normally and releases its retained state.
+ settling = bidi.send(
+ "script.evaluate",
+ {
+ "target": {"context": context},
+ "expression": "new Promise(resolve => { window.finishBiDi = resolve; })",
+ "awaitPromise": True,
+ },
+ )
+ bidi.evaluate(context, "finishBiDi(42)")
+ result = bidi.response(settling)
+ assert result["type"] == "success" and result["result"]["result"]["value"] == 42, result
+
+ # Destroying the original environment completes the unreachable promise outside garbage collection.
+ bidi.command(
+ "browsingContext.navigate", {"context": context, "url": "about:blank?next", "wait": "complete"}
+ )
+ result = bidi.response(pending)
+ assert result["type"] == "error" and result["error"] == "unknown error", result
+
+ # Preloads run once in each real document, including child documents.
+ bidi.command(
+ "script.addPreloadScript",
+ {"functionDeclaration": "() => { window.preloadCount = (window.preloadCount ?? 0) + 1; }"},
+ )
+ bidi.command(
+ "browsingContext.navigate", {"context": context, "url": "about:blank?preload", "wait": "complete"}
+ )
+ assert bidi.evaluate(context, "preloadCount")["result"]["value"] == 1
+ created = bidi.command("browsingContext.create", {"type": "tab"})["context"]
+ assert bidi.evaluate(created, "preloadCount")["result"]["value"] == 1
+ result = bidi.evaluate(
+ context,
+ "new Promise(resolve => { const frame = document.createElement('iframe'); frame.onload = () => resolve(frame.contentWindow.preloadCount); frame.src = 'about:blank?child'; document.body.append(frame); })",
+ awaitPromise=True,
+ )
+ assert result["result"]["value"] == 1, result
+
+ check_viewport_changes(bidi, connection, session_id, context, created)
+
+ bidi.command(
+ "session.subscribe",
+ {"events": ["browsingContext.navigationStarted", "browsingContext.navigationAborted"]},
+ )
+ # A top-level reload answers with the navigation ID announced before its document loads.
+ for wait in ["none", "interactive", "complete"]:
+ result = bidi.command("browsingContext.reload", {"context": context, "wait": wait})
+ started = bidi.event("browsingContext.navigationStarted")
+ assert result["navigation"] == started["navigation"] and result["navigation"] is not None, result
+ assert bidi.evaluate(context, "preloadCount")["result"]["value"] == 1
+
+ # Replacing a reload that is still waiting for its response cancels the old waiter.
+ reload_url = f"http://127.0.0.1:{server.server_port}/reload"
+ bidi.command("browsingContext.navigate", {"context": context, "url": reload_url, "wait": "complete"})
+ # Consume the navigate event before checking the two reloads.
+ bidi.event("browsingContext.navigationStarted")
+ server.block_reload = True
+ previous_reload = bidi.send("browsingContext.reload", {"context": context, "wait": "complete"})
+ assert server.request_received.wait(30), "The reload did not request its document"
+ previous_started = bidi.event("browsingContext.navigationStarted")
+ replacement_reload = bidi.send("browsingContext.reload", {"context": context, "wait": "complete"})
+ result = bidi.response(previous_reload)
+ assert result["type"] == "error" and result["error"] == "unknown error", result
+ # A command in the still-active document is an event-loop barrier while both responses are held.
+ bidi.evaluate(context, "document.URL")
+ assert replacement_reload not in bidi.responses, bidi.responses
+ server.release_response.set()
+ replacement_started = bidi.event("browsingContext.navigationStarted")
+ assert replacement_started["navigation"] != previous_started["navigation"], replacement_started
+ result = bidi.response(replacement_reload)
+ assert result["type"] == "success", result
+ assert result["result"] == {"navigation": replacement_started["navigation"], "url": reload_url}, result
+
+ # A different navigation cannot supply the held reload's result or navigation ID.
+ server.request_received.clear()
+ server.release_response.clear()
+ held_reload = bidi.send("browsingContext.reload", {"context": context, "wait": "complete"})
+ held_started = bidi.event("browsingContext.navigationStarted")
+ assert server.request_received.wait(30), "The reload did not request its document"
+ other_navigation = bidi.send(
+ "browsingContext.navigate", {"context": context, "url": "about:blank?replacement", "wait": "complete"}
+ )
+ other_started = bidi.event("browsingContext.navigationStarted")
+ assert held_started["navigation"] != other_started["navigation"], other_started
+ bidi.evaluate(context, "document.URL")
+ if held_reload in bidi.responses:
+ assert bidi.responses[held_reload]["type"] == "error", bidi.responses[held_reload]
+ server.release_response.set()
+ held_result = bidi.response(held_reload)
+ assert held_result["type"] == "error" and held_result["error"] == "unknown error", held_result
+ other_result = bidi.response(other_navigation)
+ assert other_result["type"] == "success", other_result
+ assert other_result["result"]["navigation"] == other_started["navigation"], other_result
+
+ # Ending a session also releases an outstanding evaluation and its promise.
+ bidi.send(
+ "script.evaluate",
+ {"target": {"context": context}, "expression": "new Promise(() => {})", "awaitPromise": True},
+ )
+ bidi.evaluate(context, "internals.gc(); undefined")
+ status, payload, _ = helpers.request(connection, "DELETE", f"/session/{session_id}")
+ assert status == 200, payload
+ session_id = None
+ finally:
+ cleanup_resources(server, webdriver, connection, bidi, session_id, primary_error=sys.exc_info()[1])
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("webdriver_binary")
+ run_test(parser.parse_args().webdriver_binary)