Truly independent web browser
LibWeb: Create a navigation's document when it is made active
Shannon Boothfff9d8c8a6d3
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex d96aebbf73b..870973cbbef 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -414,32 +414,14 @@ Document::HTMLCollectionAttributeInvalidationTypes Document::html_collection_attGC_DEFINE_ALLOCATOR(Document);-// https://html.spec.whatwg.org/multipage/browsers.html#obtain-browsing-context-navigation-// NB: The UI process performed this algorithm and selected this process. It names the group of the new top-level-// browsing context when it switched browsing context groups.-static GC::Ref<HTML::BrowsingContext> obtain_a_browsing_context_to_use_for_a_navigation_response(HTML::NavigationParams const& navigation_params)-{- // 1. Let browsingContext be navigationParams's navigable's active browsing context.- auto& navigable = *navigation_params.navigable;- auto browsing_context = navigable.active_browsing_context();-- // NB: Steps 2 to 9 decide whether to switch browsing context groups, and return browsingContext otherwise.- if (!navigation_params.new_browsing_context_group_id.has_value())- return *browsing_context;-- // 10. Let newBrowsingContext be the first return value of creating a new top-level browsing context and document.- auto new_browsing_context = HTML::BrowsingContext::create_a_new_browsing_context_and_document(navigable.page(), nullptr, nullptr).browsing_context;- new_browsing_context->set_browsing_context_group_id(*navigation_params.new_browsing_context_group_id);-- // 15. Return newBrowsingContext.- return new_browsing_context;-}-// https://html.spec.whatwg.org/multipage/document-lifecycle.html#initialise-the-document-objectWebIDL::ExceptionOr<GC::Ref<Document>> Document::create_and_initialize(Type type, Utf16FlyString content_type, HTML::NavigationParams const& navigation_params){// 1. Let browsingContext be the result of obtaining a browsing context to use for a navigation response given navigationParams.- auto browsing_context = obtain_a_browsing_context_to_use_for_a_navigation_response(navigation_params);+ // AD-HOC: The navigation obtained it when its response arrived. The document is created once navigable's active+ // document is unloaded, which destroys that document, and the document's link to its browsing context+ // with it.+ GC::Ref browsing_context = *navigation_params.browsing_context;// 2. Let permissionsPolicy be the result of creating a permissions policy from a response given navigationParams's// navigable's container, navigationParams's origin, and navigationParams's response.@@ -516,7 +498,8 @@ WebIDL::ExceptionOr<GC::Ref<Document>> Document::create_and_initialize(Type typetop_level_creation_url.value(),top_level_origin,agent_cluster_id,- agent_cluster_cross_origin_isolation_mode);+ agent_cluster_cross_origin_isolation_mode,+ navigation_params.environment_id);}// NB: The UI process selects the window's agent even when an initial about:blank Window is reused.@@ -6234,18 +6217,6 @@ void Document::decrement_number_of_pending_style_sheet_requests(Badge<DocumentLopage().client().request_frame_for(*this);}-// AD-HOC: A navigation can drop the document it created before activating it. Its parser and fetch go on queueing-// tasks for it that can never run, and keep it alive. A document reusing an initial about:blank's window-// shares that window with the active document, so it is left alone.-void Document::destroy_if_dropped_before_activation()-{- if (m_has_been_destroyed || is_active())- return;- if (m_browsing_context && m_browsing_context->active_window() == window().ptr())- return;- destroy();-}-void Document::set_html_parser_end_state(GC::Ptr<HTML::HTMLParserEndState> state){m_html_parser_end_state = state;@@ -6788,9 +6759,9 @@ void Document::destroy()// AD-HOC: Disentangle the ports of the window's realm, which closes the transports of the channels that document// took part in, so that the ports at their other ends learn that nothing arrives any more. A window that- // was reused for another document keeps its ports. The specification once did this here, as steps of- // destroying a document, and no longer does.- if (auto window = this->window(); window && &window->associated_document() == this)+ // was reused for another document, or that the document created once this one is unloaded takes over, keeps+ // its ports. The specification once did this here, as steps of destroying a document, and no longer does.+ if (auto window = this->window(); window && &window->associated_document() == this && !m_window_is_taken_over_after_unload)HTML::MessagePort::disentangle_ports_of_realm(HTML::relevant_realm(*window));// 4. Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications.@@ -7140,7 +7111,9 @@ void Document::ensure_style_engine_tracks_tree()}// https://html.spec.whatwg.org/multipage/document-lifecycle.html#unload-a-document-void Document::unload(GC::Ptr<Document> new_document)+// AD-HOC: A navigation's document is created once the document it replaces is unloaded. unload_of_replaced_document+// then stands in for newDocument, and keeps the unload's times until newDocument exists.+void Document::unload(GC::Ptr<Document> new_document, Optional<UnloadOfReplacedDocument>* unload_of_replaced_document){// FIXME: 1. Assert: this is running as part of a task queued on oldDocument's event loop.@@ -7148,8 +7121,9 @@ void Document::unload(GC::Ptr<Document> new_document)Optional<DocumentUnloadTimingInfo> unload_timing_info { DocumentUnloadTimingInfo {} };// 3. If newDocument is not given, then set unloadTimingInfo to null.- if (!new_document)+ if (!new_document && !unload_of_replaced_document)unload_timing_info.clear();+ HighResolutionTime::DOMHighResTimeStamp unload_event_start_shared_time = 0;// 4. Otherwise, if newDocument's event loop is not oldDocument's event loop, then the user agent may be unloading// oldDocument in parallel. In that case, the user agent should set unloadTimingInfo to null.@@ -7195,10 +7169,11 @@ void Document::unload(GC::Ptr<Document> new_document)// 11. If unloadTimingInfo is not null, then set unloadTimingInfo's unload event start time to the current high// resolution time given newDocument's relevant global object, coarsened given oldDocument's relevant settings// object's cross-origin isolated capability.- if (unload_timing_info.has_value()) {- VERIFY(new_document);+ if (unload_timing_info.has_value() && new_document) {auto current_high_resolution_time = HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*new_document));unload_timing_info->unload_event_start_time = HighResolutionTime::coarsen_time(current_high_resolution_time, HTML::relevant_settings_object(*this).cross_origin_isolated_capability());+ } else if (unload_timing_info.has_value()) {+ unload_event_start_shared_time = HighResolutionTime::unsafe_shared_current_time();}// 12. If oldDocument's salvageable state is false, then fire an event named unload at oldDocument's relevant global@@ -7213,10 +7188,16 @@ void Document::unload(GC::Ptr<Document> new_document)// 13. If unloadTimingInfo is not null, then set unloadTimingInfo's unload event end time to the current high// resolution time given newDocument's relevant global object, coarsened given oldDocument's relevant settings// object's cross-origin isolated capability.- if (unload_timing_info.has_value()) {- VERIFY(new_document);+ if (unload_timing_info.has_value() && new_document) {auto current_high_resolution_time = HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*new_document));unload_timing_info->unload_event_end_time = HighResolutionTime::coarsen_time(current_high_resolution_time, HTML::relevant_settings_object(*this).cross_origin_isolated_capability());+ } else if (unload_timing_info.has_value()) {+ *unload_of_replaced_document = UnloadOfReplacedDocument {+ .origin = origin(),+ .cross_origin_isolated_capability = HTML::relevant_settings_object(*this).cross_origin_isolated_capability(),+ .unload_event_start_time = unload_event_start_shared_time,+ .unload_event_end_time = HighResolutionTime::unsafe_shared_current_time(),+ };}// 14. Decrease eventLoop's termination nesting level by 1.@@ -7254,6 +7235,28 @@ void Document::unload(GC::Ptr<Document> new_document)did_stop_being_active_document_in_navigable();}+// https://html.spec.whatwg.org/multipage/document-lifecycle.html#unload-a-document+void Document::take_unload_timing_of_replaced_document(UnloadOfReplacedDocument const& unload)+{+ // 11. If unloadTimingInfo is not null, then set unloadTimingInfo's unload event start time to the current high+ // resolution time given newDocument's relevant global object, coarsened given oldDocument's relevant settings+ // object's cross-origin isolated capability.+ // 13. If unloadTimingInfo is not null, then set unloadTimingInfo's unload event end time to the current high+ // resolution time given newDocument's relevant global object, coarsened given oldDocument's relevant settings+ // object's cross-origin isolated capability.+ auto& global = HTML::relevant_global_object(*this);+ DocumentUnloadTimingInfo unload_timing_info {+ .unload_event_start_time = HighResolutionTime::coarsen_time(HighResolutionTime::relative_high_resolution_time(unload.unload_event_start_time, global), unload.cross_origin_isolated_capability),+ .unload_event_end_time = HighResolutionTime::coarsen_time(HighResolutionTime::relative_high_resolution_time(unload.unload_event_end_time, global), unload.cross_origin_isolated_capability),+ };++ // 22. If newDocument is given, newDocument's was created via cross-origin redirects is false, and newDocument's+ // origin is the same as oldDocument's origin, then set newDocument's previous document unload timing to+ // unloadTimingInfo.+ if (!m_was_created_via_cross_origin_redirects && origin().is_same_origin(unload.origin))+ set_previous_document_unload_timing(unload_timing_info);+}+// https://w3c.github.io/webappsec-permissions-policy/#algo-is-feature-enabledstatic PermissionsPolicy::FeatureValue is_feature_enabled_in_document_for_origin(PolicyControlledFeature feature, Document const& document, URL::Origin const& origin){diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex d83c8b0146e..38e27dad6d6 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -296,6 +296,14 @@ struct DocumentUnloadTimingInfo {HighResolutionTime::DOMHighResTimeStamp unload_event_end_time { 0 };};+// The times are unsafe shared current times, as the document they are relative to is created after the unload.+struct UnloadOfReplacedDocument {+ URL::Origin origin;+ HTML::CanUseCrossOriginIsolatedAPIs cross_origin_isolated_capability { HTML::CanUseCrossOriginIsolatedAPIs::No };+ HighResolutionTime::DOMHighResTimeStamp unload_event_start_time { 0 };+ HighResolutionTime::DOMHighResTimeStamp unload_event_end_time { 0 };+};+using PolicyControlledFeature = PermissionsPolicy::PolicyControlledFeature;struct PendingFullscreenEvent {@@ -1203,7 +1211,6 @@ public:// https://html.spec.whatwg.org/multipage/document-lifecycle.html#destroy-a-documentvoid destroy();- void destroy_if_dropped_before_activation();// https://html.spec.whatwg.org/multipage/document-lifecycle.html#destroy-a-document-and-its-descendantsvoid destroy_a_document_and_its_descendants(GC::Ptr<GC::Function<void()>> after_all_destruction = {});@@ -1213,7 +1220,9 @@ public:void abort_a_document_and_its_descendants();// https://html.spec.whatwg.org/multipage/document-lifecycle.html#unload-a-document- void unload(GC::Ptr<Document> new_document = nullptr);+ void unload(GC::Ptr<Document> new_document = nullptr, Optional<UnloadOfReplacedDocument>* unload_of_replaced_document = nullptr);+ void take_unload_timing_of_replaced_document(UnloadOfReplacedDocument const&);+ void set_window_is_taken_over_after_unload() { m_window_is_taken_over_after_unload = true; }// https://html.spec.whatwg.org/multipage/dom.html#active-parserGC::Ptr<HTML::HTMLParser> active_parser() const;@@ -2194,6 +2203,8 @@ private:// https://html.spec.whatwg.org/multipage/browsing-the-web.html#concept-document-salvageablebool m_salvageable { true };+ bool m_window_is_taken_over_after_unload { false };+// https://html.spec.whatwg.org/multipage/document-lifecycle.html#page-showingbool m_page_showing { false };diff --git a/Libraries/LibWeb/DOM/DocumentLoading.cpp b/Libraries/LibWeb/DOM/DocumentLoading.cppindex cb91cb41c52..42b0895bc4f 100644--- a/Libraries/LibWeb/DOM/DocumentLoading.cpp+++ b/Libraries/LibWeb/DOM/DocumentLoading.cpp@@ -486,7 +486,6 @@ static GC::Ref<DOM::Document> load_pdf_document(HTML::NavigationParams const& nastatic NeverDestroyed<ByteBuffer> viewer_bytes { MUST(Core::Resource::load_from_uri("resource://ladybird/pdfjs/web/viewer.html"sv))->clone_data() };auto document = MUST(DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html"_utf16_fly_string, navigation_params));- document->set_origin(URL::Origin("resource"_string, String {}, {}));add_pdf_viewer_ready_listener(document, GC::Ref(*navigation_params.response));@@ -529,20 +528,22 @@ bool can_load_document_with_type(MimeSniff::MimeType const& type)}// https://html.spec.whatwg.org/multipage/browsing-the-web.html#loading-a-document-GC::Ptr<DOM::Document> load_document(HTML::NavigationParams const& navigation_params, ReadonlyBytes sniff_bytes)+// AD-HOC: This returns the document to create in place of the Document, which is created once navigationParams's+// navigable's active document is unloaded.+GC::Ptr<HTML::DocumentToCreate> load_document(GC::Ref<HTML::NavigationParams> navigation_params, ReadonlyBytes sniff_bytes){// To load a document given navigation params navigationParams, source snapshot params sourceSnapshotParams,// and origin initiatorOrigin, perform the following steps. They return a Document or null.// 1. Let type be the computed type of navigationParams's response.- auto supplied_type = Fetch::Infrastructure::extract_mime_type(navigation_params.response->header_list());+ auto supplied_type = Fetch::Infrastructure::extract_mime_type(navigation_params->response->header_list());auto type = MimeSniff::Resource::sniff(sniff_bytes,MimeSniff::SniffingConfiguration {.sniffing_context = MimeSniff::SniffingContext::Browsing,.supplied_type = move(supplied_type) });- VERIFY(navigation_params.response->body());+ VERIFY(navigation_params->response->body());// 2. If the user agent has been configured to process resources of the given type using some mechanism other than// rendering the content in a navigable, then skip this step.@@ -551,14 +552,18 @@ GC::Ptr<DOM::Document> load_document(HTML::NavigationParams const& navigation_pa// -> an HTML MIME typeif (type.is_html()) {// Return the result of loading an HTML document, given navigationParams.- return load_html_document(navigation_params).release_value_but_fixme_should_propagate_errors();+ return HTML::DocumentToCreate::create(navigation_params, GC::create_function(GC::Heap::the(), [](HTML::NavigationParams const& navigation_params) -> GC::Ref<DOM::Document> {+ return load_html_document(navigation_params).release_value_but_fixme_should_propagate_errors();+ }));}// -> an XML MIME type that is not an explicitly supported XML MIME type// FIXME: that is not an explicitly supported XML MIME typeif (type.is_xml()) {// Return the result of loading an XML document given navigationParams and type.- return load_xml_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();+ return HTML::DocumentToCreate::create(navigation_params, GC::create_function(GC::Heap::the(), GC::captures(type), [](auto& type, HTML::NavigationParams const& navigation_params) -> GC::Ref<DOM::Document> {+ return load_xml_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();+ }));}// -> a JavaScript MIME type@@ -572,7 +577,9 @@ GC::Ptr<DOM::Document> load_document(HTML::NavigationParams const& navigation_pa|| type.essence() == "text/plain"_string|| type.essence() == "text/vtt"_string) {// Return the result of loading a text document given navigationParams and type.- return load_text_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();+ return HTML::DocumentToCreate::create(navigation_params, GC::create_function(GC::Heap::the(), GC::captures(type), [](auto& type, HTML::NavigationParams const& navigation_params) -> GC::Ref<DOM::Document> {+ return load_text_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();+ }));}// -> "multipart/x-mixed-replace"@@ -585,14 +592,21 @@ GC::Ptr<DOM::Document> load_document(HTML::NavigationParams const& navigation_paif (type.is_image()|| type.is_audio_or_video()) {// Return the result of loading a media document given navigationParams and type.- return load_media_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();+ return HTML::DocumentToCreate::create(navigation_params, GC::create_function(GC::Heap::the(), GC::captures(type), [](auto& type, HTML::NavigationParams const& navigation_params) -> GC::Ref<DOM::Document> {+ return load_media_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();+ }));}// -> "application/pdf"// -> "text/pdf"if (type.essence() == "application/pdf"_string|| type.essence() == "text/pdf"_string) {- return load_pdf_document(navigation_params);+ // AD-HOC: The PDF viewer runs with an origin of its own.+ return HTML::DocumentToCreate::create(+ navigation_params, GC::create_function(GC::Heap::the(), [](HTML::NavigationParams const& navigation_params) -> GC::Ref<DOM::Document> {+ return load_pdf_document(navigation_params);+ }),+ URL::Origin("resource"_string, String {}, {}));}// Otherwise, proceed onward.diff --git a/Libraries/LibWeb/DOM/DocumentLoading.h b/Libraries/LibWeb/DOM/DocumentLoading.hindex 8b96ba7aafc..0c1e7bda629 100644--- a/Libraries/LibWeb/DOM/DocumentLoading.h+++ b/Libraries/LibWeb/DOM/DocumentLoading.h@@ -18,12 +18,13 @@ namespace Web {enum class XMLScriptingSupport;bool build_xml_document(DOM::Document& document, ByteBuffer const& data, Optional<StringView> content_encoding, XMLScriptingSupport);-GC::Ptr<DOM::Document> load_document(HTML::NavigationParams const& navigation_params, ReadonlyBytes sniff_bytes);+GC::Ptr<HTML::DocumentToCreate> load_document(GC::Ref<HTML::NavigationParams> navigation_params, ReadonlyBytes sniff_bytes);bool can_load_document_with_type(MimeSniff::MimeType const&);// https://html.spec.whatwg.org/multipage/document-lifecycle.html#read-ua-inline-template<typename MutateDocument>-GC::Ref<DOM::Document> create_document_for_inline_content(GC::Ptr<HTML::LocalNavigable> navigable, Optional<Utf16String> navigation_id, Bindings::NavigationTimingType navigation_timing_type, HTML::UserNavigationInvolvement user_involvement, URL::Origin origin, Optional<HTML::CrossProcessId> document_id, MutateDocument mutate_document)+// AD-HOC: Steps 1 to 4 run when the navigation's response arrives. Steps 5 to 8 run in+// create_document_for_inline_content() once navigable's active document is unloaded.+inline GC::Ref<HTML::NavigationParams> create_navigation_params_for_inline_content(GC::Ptr<HTML::LocalNavigable> navigable, Optional<Utf16String> navigation_id, Bindings::NavigationTimingType navigation_timing_type, HTML::UserNavigationInvolvement user_involvement, URL::Origin origin, Optional<HTML::CrossProcessId> document_id){VERIFY(navigable->active_document());@@ -81,7 +82,14 @@ GC::Ref<DOM::Document> create_document_for_inline_content(GC::Ptr<HTML::LocalNavOptionalNone {},user_involvement);navigation_params->document_id = document_id;+ return navigation_params;+}+// https://html.spec.whatwg.org/multipage/document-lifecycle.html#read-ua-inline+// AD-HOC: Steps 5 to 8, given the navigationParams create_navigation_params_for_inline_content() made.+template<typename MutateDocument>+GC::Ref<DOM::Document> create_document_for_inline_content(HTML::NavigationParams const& navigation_params, MutateDocument mutate_document)+{// 5. Let document be the result of creating and initializing a Document object given "html", "text/html", and navigationParams.auto document = DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html"_utf16_fly_string, navigation_params).release_value_but_fixme_should_propagate_errors();diff --git a/Libraries/LibWeb/HTML/HistoryExecutor.cpp b/Libraries/LibWeb/HTML/HistoryExecutor.cppindex 8e4b9eb362a..fdded13ebd4 100644--- a/Libraries/LibWeb/HTML/HistoryExecutor.cpp+++ b/Libraries/LibWeb/HTML/HistoryExecutor.cpp@@ -36,9 +36,12 @@ struct ChangingNavigableContinuationState : public GC::Cell {bool update_only = false;Optional<Bindings::NavigationType> navigation_type;- GC::Ptr<DOM::Document> pending_document;+ GC::Ptr<DocumentToCreate> pending_document;GC::Ptr<PopulateSessionHistoryEntryDocumentOutput> population_output;GC::Ptr<DOM::Document> target_document;+ // targetEntry's document, to be created once displayedDocument is unloaded.+ GC::Ptr<DocumentToCreate> target_document_to_create;+ Optional<DOM::UnloadOfReplacedDocument> unload_of_replaced_document;UserNavigationInvolvement user_involvement { UserNavigationInvolvement::None };virtual void visit_edges(Cell::Visitor& visitor) override@@ -49,12 +52,19 @@ struct ChangingNavigableContinuationState : public GC::Cell {visitor.visit(pending_document);visitor.visit(population_output);visitor.visit(target_document);+ visitor.visit(target_document_to_create);}};GC_DEFINE_ALLOCATOR(ChangingNavigableContinuationState);GC_DEFINE_ALLOCATOR(HistoryExecutor);+static void discard_document_to_create(ChangingNavigableContinuationState const& continuation)+{+ if (auto document_to_create = continuation.target_document_to_create)+ document_to_create->discard();+}+HistoryExecutor::HistoryExecutor(Page& page): m_page(page){@@ -118,9 +128,9 @@ void HistoryExecutor::complete_ui_history_operation(CrossProcessId operation_id,auto local_target_entry = move(operation->value.local_target_entry);auto on_complete = operation->value.on_complete;- // AD-HOC: A canceled or stale operation drops the documents it populated without activating them.- GC::RootVector<GC::Ref<DOM::Document>> populated_documents;- auto append_populated_document = [&](GC::Ptr<DOM::Document> document) {+ // AD-HOC: A canceled or stale operation discards the documents it was to create.+ GC::RootVector<GC::Ref<DocumentToCreate>> populated_documents;+ auto append_populated_document = [&](GC::Ptr<DocumentToCreate> document) {if (document)populated_documents.append(*document);};@@ -128,9 +138,7 @@ void HistoryExecutor::complete_ui_history_operation(CrossProcessId operation_id,for (auto const& job : operation->value.changing_navigable_jobs) {if (!job.value.continuation)continue;- append_populated_document(job.value.continuation->pending_document);- if (auto population_output = job.value.continuation->population_output)- append_populated_document(population_output->document);+ append_populated_document(job.value.continuation->target_document_to_create);}m_history_operations.remove(operation);@@ -141,7 +149,7 @@ void HistoryExecutor::complete_ui_history_operation(CrossProcessId operation_id,}for (auto& document : populated_documents)- document->destroy_if_dropped_before_activation();+ document->discard();if (target_entry_step.has_value()&& local_target_navigable_id.has_value()@@ -258,7 +266,7 @@ static bool is_same_document_push_or_replace(Optional<Bindings::NavigationType>return target_entry.document_state()->document_id() == displayed_document.unique_id();}-static void queue_apply_history_step_task(GC::Ref<LocalNavigable> navigable, GC::Ref<GC::Function<void()>> steps)+static void queue_apply_history_step_task(GC::Ref<LocalNavigable> navigable, GC::Ref<GC::Function<void()>> steps, GC::Ptr<GC::Function<void()>> discard_steps = {}){// AD-HOC: Queue the task with navigable's active Document instead of using queue_global_task(active_window). During// initial about:blank Window reuse, active_window()->associated_document() can already be the pending@@ -266,7 +274,7 @@ static void queue_apply_history_step_task(GC::Ref<LocalNavigable> navigable, GC:// NB: The task does not run while the Document is not fully active, as once its navigable is destroyed, which leaves// its job without a reply. The UI process ends the jobs of a navigable it removes, and of a document another// operation replaces.- queue_a_task(Task::Source::NavigationAndTraversal, nullptr, navigable->active_document(), steps);+ queue_a_task(Task::Source::NavigationAndTraversal, nullptr, navigable->active_document(), steps, Task::Priority::Normal, discard_steps);}bool HistoryExecutor::resume_history_navigation_population(CrossProcessId operation_id, HistoryNavigationPopulation&& population)@@ -286,6 +294,8 @@ void HistoryExecutor::enqueue_changing_navigable_continuation(CrossProcessId ope{if (auto* operation = find_history_operation(operation_id))operation->changing_navigable_jobs.get(continuation->navigable->id())->continuation = continuation;+ else+ discard_document_to_create(continuation);on_complete->function()(ChangingNavigableHistoryStepJobDisposition::Ready, continuation->update_only);}@@ -297,11 +307,11 @@ GC::Ref<HistoryExecutor::AfterDocumentPopulated> HistoryExecutor::after_documentchanging_navigable_continuation->population_output = output;// NB: Population that produces no document leaves targetEntry's document as it was.- if (output && output->document)- changing_navigable_continuation->target_document = output->document;+ if (output && output->document_to_create)+ changing_navigable_continuation->target_document_to_create = output->document_to_create;// 1. If targetEntry's document is null, then set changingNavigableContinuation's update-only to true.- if (!changing_navigable_continuation->target_document)+ if (!changing_navigable_continuation->target_document && !changing_navigable_continuation->target_document_to_create)changing_navigable_continuation->update_only = true;// NB: The UI process runs steps 2 and 3.@@ -350,9 +360,15 @@ GC::Ref<GC::Function<void(HistoryNavigationPopulation)>> HistoryExecutor::popularequest.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(GC::Heap::the(), GC::captures(navigable, after_document_populated), [](auto& navigable, auto& after_document_populated, GC::Ptr<PopulateSessionHistoryEntryDocumentOutput> output) {+ // NB: Nothing else holds the populated document if this task is dropped.+ auto discard_populated_document = GC::create_function(navigable->heap(), GC::captures(output), [](auto& output) {+ if (output && output->document_to_create)+ output->document_to_create->discard();+ });queue_apply_history_step_task(*navigable, GC::create_function(navigable->heap(), GC::captures(after_document_populated, output), [](auto& after_document_populated, auto& output) {after_document_populated->function()(output);- }));+ }),+ discard_populated_document);}));});}@@ -405,7 +421,7 @@ void HistoryExecutor::run_ui_changing_navigable_history_job(CrossProcessId opera// The job for the navigation this process finalizes claims the entry it created, with the document it populated.// NB: The update for a navigable's creation targets an entry the navigable retains, not the one the request gave.RefPtr<SessionHistoryEntry> local_target_entry;- GC::Ptr<DOM::Document> pending_document;+ GC::Ptr<DocumentToCreate> pending_document;if (operation.local_target_navigable_id == navigable_id && navigation_type.has_value()) {VERIFY(operation.local_target_entry);local_target_entry = operation.local_target_entry;@@ -447,7 +463,7 @@ void HistoryExecutor::run_ui_changing_navigable_history_job(CrossProcessId opera// NB: targetEntry's document, as this process has it: the document the finalized navigation populated, or the// active document if targetEntry's document state has it. Any other is null until population.- changing_navigable_continuation->target_document = pending_document;+ changing_navigable_continuation->target_document_to_create = pending_document;if (!pending_document && target_entry->document_state()->document_id() == navigable->active_document_id())changing_navigable_continuation->target_document = navigable->active_document();@@ -609,6 +625,11 @@ Optional<HistoryExecutor::DequeuedChangingNavigableContinuation> HistoryExecutorVERIFY(job.has_value() && job->continuation);GC::Ref continuation = *job->continuation;+ // NB: From here on, the continuation either creates targetEntry's document or discards it. Completing the+ // operation no longer does.+ if (operation->pending_document == continuation->target_document_to_create)+ operation->pending_document = nullptr;+// 4. Let displayedDocument be changingNavigableContinuation's displayed document.auto displayed_document = continuation->displayed_document;@@ -620,8 +641,10 @@ Optional<HistoryExecutor::DequeuedChangingNavigableContinuation> HistoryExecutor// AD-HOC: This process can destroy the navigable, an ancestor of it, or the displayed document, before the UI// process removes it.- if (navigable->is_in_a_destroyed_subtree() || !displayed_document->navigable())+ if (navigable->is_in_a_destroyed_subtree() || !displayed_document->navigable()) {+ discard_document_to_create(continuation);return {};+ }// 7. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.auto script_history_length = history_object_length_and_index.script_history_length;@@ -650,6 +673,14 @@ Optional<HistoryExecutor::DequeuedChangingNavigableContinuation> HistoryExecutor// as its container is removed, e.g. while displayedDocument unloads. The provisional navigable is only// discarded once that navigable's subtree has unloaded, and has no container to take over until then.if (auto provisional_for = navigable->provisional_for(); provisional_for && provisional_for->is_in_a_destroyed_subtree()) {+ discard_document_to_create(continuation);+ on_complete->function()({}, {});+ return;+ }++ // AD-HOC: This process can destroy the navigable, or an ancestor of it, while displayedDocument unloads.+ if (navigable->is_in_a_destroyed_subtree()) {+ discard_document_to_create(continuation);on_complete->function()({}, {});return;}@@ -657,6 +688,7 @@ Optional<HistoryExecutor::DequeuedChangingNavigableContinuation> HistoryExecutor// NB: Only step 14.10 applies a same-document push or replace: its targetEntry's document is displayedDocument.if (is_same_document_push_or_replace(navigation_type, *target_entry, displayed_document)&& navigable->active_session_history_entry() != target_entry) {+ discard_document_to_create(continuation);on_complete->function()({}, {});return;}@@ -671,6 +703,15 @@ Optional<HistoryExecutor::DequeuedChangingNavigableContinuation> HistoryExecutorif (clear_navigable_target_name)target_entry->document_state()->set_navigable_target_name(Utf16String {});+ // AD-HOC: targetEntry's document is created now that displayedDocument is unloaded, right before it is made+ // active, so that nothing of it can be observed before then. A window reused from the initial+ // about:blank stays the about:blank's while it unloads, and is handed over just before activation.+ if (continuation->target_document_to_create && !update_only) {+ continuation->target_document = continuation->target_document_to_create->create_document();+ if (continuation->unload_of_replaced_document.has_value())+ continuation->target_document->take_unload_timing_of_replaced_document(*continuation->unload_of_replaced_document);+ }+// 1. Let previousEntry be navigable's active session history entry.auto previous_entry = navigable->active_session_history_entry();@@ -768,11 +809,18 @@ void HistoryExecutor::unload_displayed_document_and_apply_ui_changing_navigable_// perform the following steps:// NB: Use a null document so this remains runnable after displayedDocument becomes non-fully-active.queue_a_task(Task::Source::NavigationAndTraversal, nullptr, nullptr,- GC::create_function(heap(), GC::captures(GC::Ref { *dequeued->continuation->displayed_document }, dequeued->continuation->target_document, dequeued->after_potential_unloads), [](auto& displayed_document, auto& new_document, auto& after_potential_unloads) {+ GC::create_function(heap(), GC::captures(GC::Ref { *dequeued->continuation->displayed_document }, dequeued->continuation, dequeued->after_potential_unloads), [](auto& displayed_document, auto& continuation, auto& after_potential_unloads) {// FIXME: 1. If firePageSwapSteps is given, then run firePageSwapSteps.// 2. Unload document, passing along newDocument if it is not null.- displayed_document->unload(new_document);+ // AD-HOC: newDocument is created once document is unloaded.+ if (auto document_to_create = continuation->target_document_to_create) {+ if (document_to_create->takes_over_window_of(displayed_document))+ displayed_document->set_window_is_taken_over_after_unload();+ displayed_document->unload({}, &continuation->unload_of_replaced_document);+ } else {+ displayed_document->unload(continuation->target_document);+ }// 3. If afterAllUnloads was given, then run it.after_potential_unloads->function()();diff --git a/Libraries/LibWeb/HTML/HistoryExecutor.h b/Libraries/LibWeb/HTML/HistoryExecutor.hindex f06cc53a926..b3d2b1eff2a 100644--- a/Libraries/LibWeb/HTML/HistoryExecutor.h+++ b/Libraries/LibWeb/HTML/HistoryExecutor.h@@ -30,6 +30,7 @@namespace Web::HTML {struct ChangingNavigableContinuationState;+class DocumentToCreate;struct PopulateSessionHistoryEntryDocumentOutput;// The renderer's share of session history operations for the documents a Page hosts. The UI process owns the@@ -41,7 +42,7 @@ class WEB_API HistoryExecutor final : public GC::Cell {public:struct HistoryOperationState {- GC::Ptr<DOM::Document> pending_document {};+ GC::Ptr<DocumentToCreate> pending_document {};Optional<CrossProcessId> local_target_navigable_id {};RefPtr<SessionHistoryEntry> local_target_entry {};GC::Ptr<GC::Function<void()>> on_complete {};diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex 2fff2962fa4..65cd2d21ed7 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -666,19 +666,19 @@ void PopulateSessionHistoryEntryDocumentOutput::apply_to(NonnullRefPtr<SessionHi// Step from populate_session_history_entry_document()// 7. If entry's document state's document is not null, then:- if (document) {- entry->document_state()->set_document_id(document->unique_id());-+ // AD-HOC: The document is created once the document it replaces is unloaded, which records it in entry's document+ // state. What these steps read of it is read from what it is created from.+ if (document_to_create) {// 1. Set entry's document state's ever populated to true.entry->document_state()->set_ever_populated(true);// 2. If saveExtraDocumentState is true:if (save_extra_document_state) {// 1. Set entry's document state's origin to document's origin.- entry->document_state()->set_origin(document->origin());+ entry->document_state()->set_origin(document_to_create->origin());// 2. If document's URL requires storing the policy container in history, then:- if (url_requires_storing_the_policy_container_in_history(document->url())) {+ if (url_requires_storing_the_policy_container_in_history(document_to_create->url())) {// 1. Assert: navigationParams is a navigation params (i.e., neither null nor a non-fetch scheme navigation params).VERIFY(navigation_params.has<GC::Ref<NavigationParams>>());@@ -704,7 +704,7 @@ void PopulateSessionHistoryEntryDocumentOutput::apply_to(NonnullRefPtr<SessionHivoid PopulateSessionHistoryEntryDocumentOutput::visit_edges(Cell::Visitor& visitor){Base::visit_edges(visitor);- visitor.visit(document);+ visitor.visit(document_to_create);visitor.visit(navigation_params);}@@ -1035,8 +1035,8 @@ void LocalNavigable::continue_navigation_at_population(NavigationPopulationRequeGC::create_function(navigable->heap(), GC::captures(navigable, history_entry, request.history_handling, request.navigation_id, request.user_involvement), [](auto& navigable, auto& history_entry, auto& history_handling, auto& navigation_id, auto& user_involvement, GC::Ptr<PopulateSessionHistoryEntryDocumentOutput> output) {// AD-HOC: This check is not in the spec but we should not continue navigation if ongoing navigation id has changed.if (navigable->ongoing_navigation() != navigation_id) {- if (output && output->document)- output->document->destroy_if_dropped_before_activation();+ if (output && output->document_to_create)+ output->document_to_create->discard();navigable->stop_delaying_load_events_for_navigation(navigation_id);navigable->page().client().navigation_population_failed(navigable->id(), navigation_id);return;@@ -1052,7 +1052,7 @@ void LocalNavigable::continue_navigation_at_population(NavigationPopulationRequeif (output)output->apply_to(*history_entry);- auto pending_document = output ? output->document : GC::Ptr<DOM::Document> {};+ auto pending_document = output ? output->document_to_create : GC::Ptr<DocumentToCreate> {};// AD-HOC: Clear the ongoing navigation, like the "navigation must be a replace" and download cases do.// No history step will be applied for this navigation, so nothing else clears it, and WebDriver@@ -2152,7 +2152,7 @@ static void hand_off_to_external_software(URL::URL const& resource, GC::Ref<Loca}// https://html.spec.whatwg.org/multipage/browsing-the-web.html#attempt-to-create-a-non-fetch-scheme-document-static GC::Ptr<DOM::Document> attempt_to_create_a_non_fetch_scheme_document(NonFetchSchemeNavigationParams const& params)+static GC::Ptr<DocumentToCreate> attempt_to_create_a_non_fetch_scheme_document(NonFetchSchemeNavigationParams const& params){// 1. Let url be navigationParams's URL.auto const& url = params.url;@@ -3068,24 +3068,137 @@ void LocalNavigable::populate_session_history_entry_document(NavigationPopulatioreceived_navigation_params);}+GC_DEFINE_ALLOCATOR(DocumentToCreate);++DocumentToCreate::DocumentToCreate(GC::Ref<NavigationParams> navigation_params, GC::Ref<LoadSteps> load_steps, Optional<URL::Origin> origin)+ : m_navigation_params(navigation_params)+ , m_load_steps(load_steps)+ , m_origin(move(origin))+ , m_environment_id(navigation_params->reserved_environment ? navigation_params->reserved_environment->id : *navigation_params->environment_id)+{+}++void DocumentToCreate::visit_edges(Cell::Visitor& visitor)+{+ Base::visit_edges(visitor);+ visitor.visit(m_navigation_params);+ visitor.visit(m_load_steps);+}++URL::Origin DocumentToCreate::origin() const+{+ return m_origin.value_or(m_navigation_params->origin);+}++// https://html.spec.whatwg.org/multipage/document-lifecycle.html#initialise-the-document-object+URL::URL DocumentToCreate::url() const+{+ // 3. Let creationURL be navigationParams's response's URL.+ // 4. If navigationParams's request is non-null, then set creationURL to navigationParams's request's+ // current URL.+ return m_navigation_params->request ? m_navigation_params->request->current_url() : m_navigation_params->response->url().value();+}++CrossProcessId DocumentToCreate::id() const+{+ return *m_navigation_params->document_id;+}++// AD-HOC: The UI process learns the id before the document is created. A window reused from the initial about:blank+// keeps its environment settings object.+EnvironmentId const& DocumentToCreate::environment_id() const+{+ if (auto const* document = m_navigation_params->browsing_context->active_document(); document && takes_over_window_of(*document))+ return document->relevant_settings_object().id;+ return m_environment_id;+}++// https://html.spec.whatwg.org/multipage/document-lifecycle.html#initialise-the-document-object+bool DocumentToCreate::takes_over_window_of(DOM::Document const& document) const+{+ if (m_navigation_params->browsing_context != document.browsing_context())+ return false;++ // 6. If browsingContext's active document's is initial about:blank is true, and browsingContext's active document's+ // origin is same origin-domain with navigationParams's origin, then set window to browsingContext's active window.+ return document.is_initial_about_blank() && document.origin().is_same_origin_domain(m_navigation_params->origin);+}++GC::Ref<DOM::Document> DocumentToCreate::create_document()+{+ auto document = m_load_steps->function()(*m_navigation_params);+ if (m_origin.has_value())+ document->set_origin(*m_origin);+ m_navigation_params->response->resume_body_delivery();+ m_navigation_params = nullptr;+ m_load_steps = nullptr;+ return document;+}++// A navigation whose document was never created releases the response body held for it.+void DocumentToCreate::discard()+{+ if (m_navigation_params)+ stop_response_body_delivery(*m_navigation_params);+ m_navigation_params = nullptr;+ m_load_steps = nullptr;+}+// NB: A document created in place of the response, or the PDF viewer, has an origin other than its navigation params'.// The process reports which of the two it created, and the UI process takes up that origin for the document it// holds.static void report_a_document_with_an_origin_of_its_own(LocalNavigable& navigable, PopulateSessionHistoryEntryDocumentOutput const& output){auto const* navigation_params = output.navigation_params.get_pointer<GC::Ref<NavigationParams>>();- if (!output.document || !navigation_params || output.document->origin().is_same_origin((*navigation_params)->origin))+ if (!output.document_to_create || !navigation_params || output.document_to_create->origin().is_same_origin((*navigation_params)->origin))return;- auto origin = output.inline_content_origin.has_value() && output.document->origin().is_same_origin(*output.inline_content_origin)+ auto origin = output.inline_content_origin.has_value() && output.document_to_create->origin().is_same_origin(*output.inline_content_origin)? PopulatedDocumentOrigin::InlineContent: PopulatedDocumentOrigin::PdfViewer;- navigable.page().client().page_did_create_populated_document_with_an_origin_of_its_own(navigable.id(), output.document->id(), origin, output.document->relevant_settings_object().id);+ navigable.page().client().page_did_create_populated_document_with_an_origin_of_its_own(navigable.id(), output.document_to_create->id(), origin, output.document_to_create->environment_id());+}++// https://html.spec.whatwg.org/multipage/browsers.html#obtain-browsing-context-navigation+// NB: The UI process performed this algorithm and selected this process. It names the group of the new top-level+// browsing context when it switched browsing context groups.+static GC::Ref<HTML::BrowsingContext> obtain_a_browsing_context_to_use_for_a_navigation_response(HTML::NavigationParams const& navigation_params)+{+ // 1. Let browsingContext be navigationParams's navigable's active browsing context.+ auto& navigable = *navigation_params.navigable;+ auto browsing_context = navigable.active_browsing_context();++ // NB: Steps 2 to 9 decide whether to switch browsing context groups, and return browsingContext otherwise.+ if (!navigation_params.new_browsing_context_group_id.has_value())+ return *browsing_context;++ // 10. Let newBrowsingContext be the first return value of creating a new top-level browsing context and document.+ auto new_browsing_context = HTML::BrowsingContext::create_a_new_browsing_context_and_document(navigable.page(), nullptr, nullptr).browsing_context;+ new_browsing_context->set_browsing_context_group_id(*navigation_params.new_browsing_context_group_id);++ // 15. Return newBrowsingContext.+ return new_browsing_context;}-static GC::Ref<DOM::Document> create_navigation_error_document(LocalNavigable& navigable, Optional<Utf16String> const& navigation_id, Bindings::NavigationTimingType navigation_timing_type, UserNavigationInvolvement user_involvement, URL::Origin const& origin, Optional<CrossProcessId> document_id, URL::URL const& url, Utf16String const& error_message)+GC::Ref<DocumentToCreate> DocumentToCreate::create(GC::Ref<NavigationParams> navigation_params, GC::Ref<LoadSteps> load_steps, Optional<URL::Origin> origin)+{+ // https://html.spec.whatwg.org/multipage/document-lifecycle.html#initialise-the-document-object+ // 1. Let browsingContext be the result of obtaining a browsing context to use for a navigation response given+ // navigationParams.+ // AD-HOC: Obtained now, as navigable's active document is unloaded before the document is created.+ navigation_params->browsing_context = obtain_a_browsing_context_to_use_for_a_navigation_response(*navigation_params);++ // AD-HOC: The UI process learns the id of the new Window's environment before the document is created.+ if (!navigation_params->reserved_environment && !navigation_params->environment_id.has_value())+ navigation_params->environment_id = EnvironmentId::generate();+ if (!navigation_params->document_id.has_value())+ navigation_params->document_id = navigation_params->navigable->page().client().allocate_cross_process_id();+ return GC::Heap::the().allocate<DocumentToCreate>(navigation_params, load_steps, move(origin));+}++static GC::Ref<DOM::Document> create_navigation_error_document(NavigationParams const& navigation_params, URL::URL const& url, Utf16String const& error_message){auto error_html = load_error_page(url, error_message.to_utf8()).release_value_but_fixme_should_propagate_errors();- return create_document_for_inline_content(&navigable, navigation_id, navigation_timing_type, user_involvement, origin, document_id, [error_html](auto& document) {+ auto document = create_document_for_inline_content(navigation_params, [&error_html](auto& document) {auto scripting_mode = document.is_scripting_enabled() ? HTML::ParserScriptingMode::Normal : HTML::ParserScriptingMode::Disabled;auto parser = HTMLParser::create_from_byte_string(document, error_html, scripting_mode, "utf-8"sv);document.set_url(URL::about_error());@@ -3099,6 +3212,20 @@ static GC::Ref<DOM::Document> create_navigation_error_document(LocalNavigable& nHTMLParser::the_end(document, parser);}));});++ // https://html.spec.whatwg.org/multipage/browsing-the-web.html#attempt-to-populate-the-history-entry's-document+ // 2. Make document unsalvageable given entry's document state's document and "navigation-failure".+ // AD-HOC: Run once the document is created, for this step and for the HTTP error page alike.+ document->make_unsalvageable("navigation-failure"_utf16);+ return document;+}++static GC::Ref<DocumentToCreate> navigation_error_document(LocalNavigable& navigable, Optional<Utf16String> const& navigation_id, Bindings::NavigationTimingType navigation_timing_type, UserNavigationInvolvement user_involvement, URL::Origin const& origin, Optional<CrossProcessId> document_id, URL::URL const& url, Utf16String const& error_message)+{+ auto navigation_params = create_navigation_params_for_inline_content(&navigable, navigation_id, navigation_timing_type, user_involvement, origin, document_id);+ return DocumentToCreate::create(navigation_params, GC::create_function(GC::Heap::the(), GC::captures(url, error_message), [](auto& url, auto& error_message, NavigationParams const& navigation_params) -> GC::Ref<DOM::Document> {+ return create_navigation_error_document(navigation_params, url, error_message);+ }));}static void load_document_or_handle_download(GC::Ref<NavigationParams> navigation_params, ReadonlyBytes sniff_bytes, URL::URL const& url, bool source_allows_downloading, Optional<URL::Origin> source_interface_origin, PopulateSessionHistoryEntryDocumentOutput& output)@@ -3114,7 +3241,7 @@ static void load_document_or_handle_download(GC::Ref<NavigationParams> navigatioauto error_message = Utf16String::formatted("HTTP error: {} {}", navigation_params->response->status(), navigation_params->response->status_message());- output.document = create_navigation_error_document(+ output.document_to_create = navigation_error_document(*navigation_params->navigable,navigation_params->id,navigation_params->navigation_timing_type,@@ -3124,18 +3251,14 @@ static void load_document_or_handle_download(GC::Ref<NavigationParams> navigatiooutput.redirected_url.value_or(url),error_message);- output.document->make_unsalvageable("navigation-failure"_utf16);-return;}- output.document = load_document(navigation_params, sniff_bytes);+ output.document_to_create = load_document(navigation_params, sniff_bytes);- if (!output.document) {+ if (!output.document_to_create) {output.download_handled = handle_navigation_response_as_download(navigation_params, source_allows_downloading, source_interface_origin);output.save_extra_document_state = false;- } else {- navigation_params->response->resume_body_delivery();}}@@ -3179,11 +3302,11 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent// document given navigationParams.// NOTE: This can result in setting entry's document state's document to null, e.g., when handing-off to// external software.- output->document = attempt_to_create_a_non_fetch_scheme_document(navigation_params.get<GC::Ref<NonFetchSchemeNavigationParams>>());+ output->document_to_create = 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())+ if (!output->document_to_create && WebDriver::BiDi::is_active())WebDriver::BiDi::navigation_event(self, "browsingContext.navigationFailed"sv, navigation_id, url);// 2. Set saveExtraDocumentState to false.@@ -3214,11 +3337,10 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent// AD-HOC: Name the URL that actually failed to load: The last URL the navigation was redirected to, if// any — rather than the URL it started at.auto error_url = output->redirected_url.value_or(url);- output->document = create_navigation_error_document(self, navigation_id, navigation_timing_type, user_involvement, output->inline_content_origin.value(), output->document_id, error_url, error_message);+ output->document_to_create = navigation_error_document(self, navigation_id, navigation_timing_type, user_involvement, output->inline_content_origin.value(), output->document_id, error_url, error_message);// 2. Make document unsalvageable given entry's document state's document and "navigation-failure".- if (output->document)- output->document->make_unsalvageable("navigation-failure"_utf16);+ // AD-HOC: That happens when the document is created.// 3. Set saveExtraDocumentState to false.output->save_extra_document_state = false;@@ -3272,10 +3394,8 @@ void LocalNavigable::queue_navigation_and_traversal_task_for_session_history_ent// AD-HOC: The document may have been destroyed between when the fetch started and when the// bytes arrived. A response that failed mid-sniff must not be loaded as a document// off its partial bytes either.- // AD-HOC: A navigation that a newer one superseded during the wait makes no document either:- // the document would take over the Window of an initial about:blank, whose tasks then- // wait for a document that never becomes active, among them those of the newer- // navigation.+ // AD-HOC: A navigation that a newer one superseded during the wait does not act on its+ // response either, which would otherwise start a download the user replaced.auto is_superseded = navigation_id.has_value() && nav_params->navigable->ongoing_navigation() != navigation_id && !is_reload_traversal;if (!is_superseded && nav_params->navigable->active_browsing_context() && sniff_bytes.outcome == Fetch::Infrastructure::Body::SniffOutcome::Complete) {load_document_or_handle_download(nav_params, sniff_bytes.bytes, url, source_allows_downloading, source_interface_origin, *output);@@ -4083,7 +4203,7 @@ void LocalNavigable::navigate_to_a_fragment(URL::URL const& url, HistoryHandling}// https://html.spec.whatwg.org/multipage/browsing-the-web.html#evaluate-a-javascript:-url-GC::Ptr<DOM::Document> LocalNavigable::evaluate_javascript_url(URL::URL const& url, URL::Origin const& new_document_origin, UserNavigationInvolvement user_involvement, Utf16String navigation_id)+GC::Ptr<DocumentToCreate> LocalNavigable::evaluate_javascript_url(URL::URL const& url, URL::Origin const& new_document_origin, UserNavigationInvolvement user_involvement, Utf16String navigation_id){auto& vm = this->vm();VERIFY(active_window());@@ -4313,7 +4433,8 @@ void LocalNavigable::navigate_to_a_javascript_url(NonnullRefPtr<Fetch::Infrastru// NB: Not one of the spec's document state fields. The entry keeps its URL, so it keeps what its fetch recorded.document_state->set_user_agent_initiated(old_doc_state->user_agent_initiated());document_state->set_navigation_same_site_status(old_doc_state->navigation_same_site_status());- document_state->set_document_id(new_document->unique_id());+ // AD-HOC: newDocument is created once the active document is unloaded, and sets documentState's document when it+ // is made active.// 12. Let historyEntry be a new session history entry, with// URL: entryToReplace's URL@@ -4450,12 +4571,12 @@ void LocalTraversableNavigable::request_close_preflight(GC::Ref<GC::Function<voi// https://html.spec.whatwg.org/multipage/browsing-the-web.html#finalize-a-cross-document-navigation// NB: The UI process appends the steps finalizing the navigation, and runs them, once this process reports that// populating historyEntry's document is over.-void finalize_a_cross_document_navigation(GC::Ref<LocalNavigable> navigable, HistoryHandlingBehavior history_handling, UserNavigationInvolvement user_involvement, NonnullRefPtr<SessionHistoryEntry> history_entry, GC::Ptr<DOM::Document> pending_document, Utf16String navigation_id)+void finalize_a_cross_document_navigation(GC::Ref<LocalNavigable> navigable, HistoryHandlingBehavior history_handling, UserNavigationInvolvement user_involvement, NonnullRefPtr<SessionHistoryEntry> history_entry, GC::Ptr<DocumentToCreate> pending_document, Utf16String navigation_id){// NOTE: This is not in the spec but we should not navigate destroyed navigable.if (navigable->has_been_destroyed()) {if (pending_document)- pending_document->destroy_if_dropped_before_activation();+ pending_document->discard();navigable->set_delaying_load_events(false);navigable->page().client().navigation_population_failed(navigable->id(), navigation_id);return;@@ -4474,7 +4595,7 @@ void finalize_a_cross_document_navigation(GC::Ref<LocalNavigable> navigable, His.navigation_id = navigation_id,.history_handling = history_handling,.user_involvement = user_involvement,- .environment_id = pending_document ? Optional<Web::HTML::EnvironmentId> { pending_document->relevant_settings_object().id } : Optional<Web::HTML::EnvironmentId> {},+ .environment_id = pending_document ? Optional<Web::HTML::EnvironmentId> { pending_document->environment_id() } : Optional<Web::HTML::EnvironmentId> {},.document_id = pending_document ? Optional<CrossProcessId> { pending_document->id() } : Optional<CrossProcessId> {},},{diff --git a/Libraries/LibWeb/HTML/LocalNavigable.h b/Libraries/LibWeb/HTML/LocalNavigable.hindex 4440efc1b4d..523819ca921 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.h+++ b/Libraries/LibWeb/HTML/LocalNavigable.h@@ -72,6 +72,7 @@ namespace Web::HTML {enum class ClockAnimations : u8;struct PopulateSessionHistoryEntryDocumentOutput;+class DocumentToCreate;// https://html.spec.whatwg.org/multipage/document-sequences.html#navigableclass WEB_API LocalNavigable : public Navigable {@@ -220,7 +221,7 @@ public:void create_navigation_params_for_navigation(NavigationPopulationRequest, GC::Ref<SourceSnapshotParams>, NavigationParamsVariant, Bindings::NavigationTimingType);- GC::Ptr<DOM::Document> evaluate_javascript_url(URL::URL const&, URL::Origin const& new_document_origin, UserNavigationInvolvement, Utf16String navigation_id);+ GC::Ptr<DocumentToCreate> evaluate_javascript_url(URL::URL const&, URL::Origin const& new_document_origin, UserNavigationInvolvement, Utf16String navigation_id);void reload(Optional<StorageSerializationRecord> navigation_api_state = {}, UserNavigationInvolvement = UserNavigationInvolvement::None, GC::Ptr<NavigationAPIMethodTracker> api_method_tracker = {});@@ -791,12 +792,46 @@ private:Vector<Web::AsyncScrollNodeStableID, 1> m_held_boxes;};+// AD-HOC: The Document a navigation creates once the document it replaces is unloaded, as what it is created from.+// What the steps before then read of the Document is read from there.+class DocumentToCreate final : public GC::Cell {+ GC_CELL(DocumentToCreate, GC::Cell);+ GC_DECLARE_ALLOCATOR(DocumentToCreate);++public:+ using LoadSteps = GC::Function<GC::Ref<DOM::Document>(NavigationParams const&)>;++ static GC::Ref<DocumentToCreate> create(GC::Ref<NavigationParams>, GC::Ref<LoadSteps>, Optional<URL::Origin> origin = {});++ URL::Origin origin() const;+ URL::URL url() const;+ CrossProcessId id() const;+ EnvironmentId const& environment_id() const;++ bool takes_over_window_of(DOM::Document const&) const;++ GC::Ref<DOM::Document> create_document();+ void discard();++private:+ DocumentToCreate(GC::Ref<NavigationParams>, GC::Ref<LoadSteps>, Optional<URL::Origin>);++ virtual void visit_edges(Cell::Visitor&) override;++ // Null once the document is created or discarded, so that what it was created from is released.+ GC::Ptr<NavigationParams> m_navigation_params;+ GC::Ptr<LoadSteps> m_load_steps;+ Optional<URL::Origin> m_origin;+ // Creating the document moves the id out of the reserved environment.+ EnvironmentId m_environment_id;+};+struct PopulateSessionHistoryEntryDocumentOutput final : public JS::Cell {GC_CELL(PopulateSessionHistoryEntryDocumentOutput, JS::Cell);GC_DECLARE_ALLOCATOR(PopulateSessionHistoryEntryDocumentOutput);public:- GC::Ptr<DOM::Document> document;+ GC::Ptr<DocumentToCreate> document_to_create;LocalNavigable::NavigationParamsVariant navigation_params { LocalNavigable::NullOrError {} };bool save_extra_document_state = true;@@ -821,7 +856,7 @@ WEB_API HashTable<GC::RawRef<LocalNavigable>>& all_local_navigables();WEB_API GC::Ptr<LocalNavigable> local_navigable_with_id(CrossProcessId);bool navigation_must_be_a_replace(URL::URL const& url, DOM::Document const& document);-void finalize_a_cross_document_navigation(GC::Ref<LocalNavigable>, HistoryHandlingBehavior, UserNavigationInvolvement, NonnullRefPtr<SessionHistoryEntry>, GC::Ptr<DOM::Document> pending_document, Utf16String navigation_id);+void finalize_a_cross_document_navigation(GC::Ref<LocalNavigable>, HistoryHandlingBehavior, UserNavigationInvolvement, NonnullRefPtr<SessionHistoryEntry>, GC::Ptr<DocumentToCreate> pending_document, Utf16String navigation_id);WEB_API void check_if_unloading_is_canceled(Page&, Vector<GC::Root<LocalNavigable>> navigables_that_need_before_unload, GC::Ptr<LocalTraversableNavigable> owner, GC::Ptr<LocalTraversableNavigable> traversable, RefPtr<SessionHistoryEntry> target_entry, Optional<UserNavigationInvolvement> user_involvement_for_navigate_events, UnloadPromptShown, GC::Ref<GC::Function<void(CheckIfUnloadingIsCanceledResult, UnloadPromptShown)>> callback);void perform_url_and_history_update_steps(DOM::Document& document, URL::URL new_url, Optional<StorageSerializationRecord> = {}, HistoryHandlingBehavior history_handling = HistoryHandlingBehavior::Replace);diff --git a/Libraries/LibWeb/HTML/NavigationParams.cpp b/Libraries/LibWeb/HTML/NavigationParams.cppindex 4cacf639474..d65259e887d 100644--- a/Libraries/LibWeb/HTML/NavigationParams.cpp+++ b/Libraries/LibWeb/HTML/NavigationParams.cpp@@ -10,6 +10,7 @@#include <LibWeb/Fetch/Engine/NetworkTransportHandle.h>#include <LibWeb/Fetch/Infrastructure/FetchController.h>#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>+#include <LibWeb/HTML/BrowsingContext.h>#include <LibWeb/HTML/LocalNavigable.h>#include <LibWeb/HTML/NavigationParams.h>#include <LibWeb/HTML/Scripting/Environments.h>@@ -27,6 +28,7 @@ void NavigationParams::visit_edges(Visitor& visitor)visitor.visit(fetch_controller);visitor.visit(commit_early_hints);visitor.visit(reserved_environment);+ visitor.visit(browsing_context);}NavigationParams::BodyDelivery NavigationParams::body_delivery() constdiff --git a/Libraries/LibWeb/HTML/NavigationParams.h b/Libraries/LibWeb/HTML/NavigationParams.hindex 9254eb7dbcc..465cc1e06e0 100644--- a/Libraries/LibWeb/HTML/NavigationParams.h+++ b/Libraries/LibWeb/HTML/NavigationParams.h@@ -86,6 +86,13 @@ struct NavigationParams : GC::Cell {// browsing context group switch gave it one.Optional<u64> new_browsing_context_group_id;+ // AD-HOC: The browsing context obtained for the new Document when the response arrived.+ GC::Ptr<BrowsingContext> browsing_context;++ // AD-HOC: The id of the new Window's environment when there is no reserved environment. The UI process learns it+ // before the Document is created.+ Optional<EnvironmentId> environment_id;+// AD-HOC: The permissions policy the UI process created for the new Document.Optional<PermissionsPolicy::PermissionsPolicy> permissions_policy;diff --git a/Libraries/LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.cpp b/Libraries/LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.cppindex ff619ee93a0..1a38c282417 100644--- a/Libraries/LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.cpp+++ b/Libraries/LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.cpp@@ -36,7 +36,7 @@ void WindowEnvironmentSettingsObject::visit_edges(JS::Cell::Visitor& visitor)}// https://html.spec.whatwg.org/multipage/window-object.html#set-up-a-window-environment-settings-object-void WindowEnvironmentSettingsObject::setup(Page& page, URL::URL const& creation_url, NonnullOwnPtr<JS::ExecutionContext> execution_context, GC::Ptr<Environment> reserved_environment, URL::URL top_level_creation_url, URL::Origin top_level_origin, Optional<u64> agent_cluster_id, CrossOriginIsolationMode agent_cluster_cross_origin_isolation_mode)+void WindowEnvironmentSettingsObject::setup(Page& page, URL::URL const& creation_url, NonnullOwnPtr<JS::ExecutionContext> execution_context, GC::Ptr<Environment> reserved_environment, URL::URL top_level_creation_url, URL::Origin top_level_origin, Optional<u64> agent_cluster_id, CrossOriginIsolationMode agent_cluster_cross_origin_isolation_mode, Optional<EnvironmentId> environment_id){// 1. Let realm be the value of execution context's Realm component.auto realm = execution_context->realm;@@ -67,7 +67,8 @@ void WindowEnvironmentSettingsObject::setup(Page& page, URL::URL const& creation// 5. Otherwise, set settings object's id to a new unique opaque string, settings object's target browsing context to// null, and settings object's active service worker to null.else {- settings_object->id = EnvironmentId::generate();+ // AD-HOC: An id the UI process already learned stands in for the new unique opaque string.+ settings_object->id = environment_id.has_value() ? environment_id.release_value() : EnvironmentId::generate();settings_object->target_browsing_context = nullptr;// FIXME: Set settings object's active service worker to null.}diff --git a/Libraries/LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h b/Libraries/LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.hindex 16494edd3cb..8d986bf8ff5 100644--- a/Libraries/LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h+++ b/Libraries/LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h@@ -16,7 +16,7 @@ class WindowEnvironmentSettingsObject final : public EnvironmentSettingsObject {GC_DECLARE_ALLOCATOR(WindowEnvironmentSettingsObject);public:- static WEB_API void setup(Page&, URL::URL const& creation_url, NonnullOwnPtr<JS::ExecutionContext>, GC::Ptr<Environment>, URL::URL top_level_creation_url, URL::Origin top_level_origin, Optional<u64> agent_cluster_id, CrossOriginIsolationMode agent_cluster_cross_origin_isolation_mode);+ static WEB_API void setup(Page&, URL::URL const& creation_url, NonnullOwnPtr<JS::ExecutionContext>, GC::Ptr<Environment>, URL::URL top_level_creation_url, URL::Origin top_level_origin, Optional<u64> agent_cluster_id, CrossOriginIsolationMode agent_cluster_cross_origin_isolation_mode, Optional<EnvironmentId> environment_id = {});virtual ~WindowEnvironmentSettingsObject() override;diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex e9e9efd0267..60c58ee60bd 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -4,6 +4,9 @@ Text/input/PDF/jbig2-image.html[LoadFromHttpServer]Text/input/HTML/unload-beacon-outlives-its-document.html+Text/input/HTML/reused-window-unload-beacon.html+Text/input/HTML/reused-window-media-document-loads.html+Text/input/HTML/reused-window-takes-its-document-after-unload.htmlText/input/wpt-import/console/console-log-large-array.any.worker.html; A data: iframe stays in this process only under an http: page.Text/input/HTML/cross-origin-rejected-promise-realm.htmldiff --git a/Tests/LibWeb/Text/expected/HTML/reused-window-media-document-loads.txt b/Tests/LibWeb/Text/expected/HTML/reused-window-media-document-loads.txtnew file mode 100644index 00000000000..50ea2bc31db--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/reused-window-media-document-loads.txt@@ -0,0 +1,2 @@+120.png: Window reused: true, img loaded: true+red-with-second-in-gray-64x36.webm: Window reused: true, video loaded: truediff --git a/Tests/LibWeb/Text/expected/HTML/reused-window-takes-its-document-after-unload.txt b/Tests/LibWeb/Text/expected/HTML/reused-window-takes-its-document-after-unload.txtnew file mode 100644index 00000000000..b32a6046603--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/reused-window-takes-its-document-after-unload.txt@@ -0,0 +1,6 @@+Window reused: true+window.document during unload is the initial about:blank: true+unload's target is the initial about:blank: true+window.document changed before contentDocument: false+New document finished loading: complete+Port of the reused Window's realm: delivereddiff --git a/Tests/LibWeb/Text/expected/HTML/reused-window-unload-beacon.txt b/Tests/LibWeb/Text/expected/HTML/reused-window-unload-beacon.txtnew file mode 100644index 00000000000..51a456eeff3--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/reused-window-unload-beacon.txt@@ -0,0 +1,3 @@+Window reused: true+Beacon queued: true+Beacon followed its redirectdiff --git a/Tests/LibWeb/Text/input/HTML/reused-window-media-document-loads.html b/Tests/LibWeb/Text/input/HTML/reused-window-media-document-loads.htmlnew file mode 100644index 00000000000..d2fb354a27c--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/reused-window-media-document-loads.html@@ -0,0 +1,22 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A media document that takes its Window over from the initial about:blank loads its media in its own context.+ asyncTest(async done => {+ for (const src of ["../../../Assets/120.png", "../../../Assets/red-with-second-in-gray-64x36.webm"]) {+ const iframe = document.createElement("iframe");+ iframe.src = src;+ document.body.append(iframe);+ const frameWindow = iframe.contentWindow;+ frameWindow.marker = true;+ await new Promise(resolve => iframe.addEventListener("load", resolve, { once: true }));+ const media = iframe.contentDocument.querySelector("img, video");+ const loaded = media.localName === "img"+ ? media.naturalWidth > 0+ : media.readyState >= HTMLMediaElement.HAVE_METADATA && media.videoWidth > 0;+ println(`${src.split("/").pop()}: Window reused: ${frameWindow.marker === true}, ${media.localName} loaded: ${loaded}`);+ iframe.remove();+ }+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/reused-window-takes-its-document-after-unload.html b/Tests/LibWeb/Text/input/HTML/reused-window-takes-its-document-after-unload.htmlnew file mode 100644index 00000000000..af693f388f4--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/reused-window-takes-its-document-after-unload.html@@ -0,0 +1,50 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A Window reused from the initial about:blank keeps the about:blank as its document until the document that takes+ // it over is made active, as in Chrome, Firefox and Safari. The about:blank still has the Window while it unloads,+ // and the Window never has a document its iframe does not show.+ asyncTest(async done => {+ const iframe = document.createElement("iframe");+ iframe.src = "../../../Assets/blank.html";+ document.body.append(iframe);+ const initialDocument = iframe.contentDocument;+ const frameWindow = iframe.contentWindow;+ frameWindow.marker = true;++ let documentDuringUnload, targetDuringUnload;+ frameWindow.addEventListener("unload", e => {+ documentDuringUnload = frameWindow.document;+ targetDuringUnload = e.target;+ });++ // Ports of the reused Window's realm stay entangled when the about:blank is destroyed.+ const channel = new frameWindow.MessageChannel();+ const portMessage = new Promise(resolve => {+ channel.port2.onmessage = e => resolve(e.data);+ });++ let windowDocumentRanAhead = false;+ await new Promise(resolve => {+ const { port1, port2 } = new MessageChannel();+ port1.onmessage = () => {+ if (frameWindow.document !== initialDocument && iframe.contentDocument === initialDocument)+ windowDocumentRanAhead = true;+ if (iframe.contentDocument !== initialDocument && iframe.contentDocument.readyState === "complete")+ return resolve();+ port2.postMessage(0);+ };+ port2.postMessage(0);+ });++ channel.port1.postMessage("delivered");++ println(`Window reused: ${frameWindow.marker === true}`);+ println(`window.document during unload is the initial about:blank: ${documentDuringUnload === initialDocument}`);+ println(`unload's target is the initial about:blank: ${targetDuringUnload === initialDocument}`);+ println(`window.document changed before contentDocument: ${windowDocumentRanAhead}`);+ println(`New document finished loading: ${iframe.contentDocument.readyState}`);+ println(`Port of the reused Window's realm: ${await portMessage}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/HTML/reused-window-unload-beacon.html b/Tests/LibWeb/Text/input/HTML/reused-window-unload-beacon.htmlnew file mode 100644index 00000000000..cfca6303758--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/reused-window-unload-beacon.html@@ -0,0 +1,51 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A beacon the initial about:blank sends as it unloads follows its redirect to the end, even though its Window goes+ // on with the document that takes it over.+ asyncTest(async done => {+ const server = httpTestServer();+ const token = `reused-window-unload-beacon-${crypto.randomUUID()}`;+ const destinationURL = await server.createEcho("POST", `/${token}/destination`, {+ status: 200,+ body: "",+ });+ const beaconURL = await server.createEcho("POST", `/${token}/beacon`, {+ status: 307,+ headers: { Location: destinationURL },+ body: "",+ wait_for_unblock: token,+ });++ const iframe = document.createElement("iframe");+ iframe.src = "../../../Assets/blank.html";+ document.body.append(iframe);+ const initialDocument = iframe.contentDocument;+ const frameWindow = iframe.contentWindow;+ frameWindow.marker = true;++ let beaconQueued = false;+ frameWindow.addEventListener("unload", () => {+ beaconQueued = frameWindow.navigator.sendBeacon(beaconURL, "unload");+ });++ await new Promise(resolve => {+ const { port1, port2 } = new MessageChannel();+ port1.onmessage = () => {+ if (iframe.contentDocument !== initialDocument && iframe.contentDocument.readyState === "complete")+ return resolve();+ port2.postMessage(0);+ };+ port2.postMessage(0);+ });++ await server.waitForRequest(beaconURL);+ await fetch(new URL(`/unblock/${token}`, server.baseURL));+ await server.waitForRequest(destinationURL);++ println(`Window reused: ${frameWindow.marker === true}`);+ println(`Beacon queued: ${beaconQueued}`);+ println("Beacon followed its redirect");+ done();+ });+</script>