Truly independent web browser
/*
* Copyright (c) 2023, Andrew Kaster <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibGC/Heap.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/Bindings/Navigation.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/DOM/AbortController.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/HTML/DocumentState.h>
#include <LibWeb/HTML/ErrorEvent.h>
#include <LibWeb/HTML/ErrorInformation.h>
#include <LibWeb/HTML/History.h>
#include <LibWeb/HTML/HistoryExecutor.h>
#include <LibWeb/HTML/LocalTraversableNavigable.h>
#include <LibWeb/HTML/NavigateEvent.h>
#include <LibWeb/HTML/Navigation.h>
#include <LibWeb/HTML/NavigationActivation.h>
#include <LibWeb/HTML/NavigationCurrentEntryChangeEvent.h>
#include <LibWeb/HTML/NavigationDestination.h>
#include <LibWeb/HTML/NavigationHistoryEntry.h>
#include <LibWeb/HTML/NavigationPrecommitController.h>
#include <LibWeb/HTML/NavigationTransition.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/ExceptionReporter.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/SessionHistoryEntry.h>
#include <LibWeb/HTML/SourceSnapshotParams.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Promise.h>
#include <LibWeb/XHR/FormData.h>
namespace Web::HTML {
GC_DEFINE_ALLOCATOR(Navigation);
GC_DEFINE_ALLOCATOR(NavigationAPIMethodTracker);
static GC::Ref<WebIDL::Promise> invoke_navigation_intercept_handler(WebIDL::CallbackType& handler)
{
return WebIDL::invoke_promise_callback(handler, {}, {});
}
static void resolve_navigation_history_entry_promise(JS::Realm& realm, WebIDL::Promise& promise, GC::Ref<NavigationHistoryEntry> entry)
{
WebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, entry));
}
static void report_navigation_api_state_update(DOM::Document& document, SessionHistoryEntry const& entry)
{
auto navigable = document.navigable();
if (!navigable)
return;
navigable->page().client().page_did_update_session_history_entry_navigation_api_state(navigable->id(), session_history_entry_identity(entry), entry.navigation_api_state());
}
NavigationAPIMethodTracker::NavigationAPIMethodTracker(GC::Ref<Navigation> navigation,
Optional<Utf16String> key,
JS::Value info,
Optional<StorageSerializationRecord> serialized_state,
GC::Ptr<NavigationHistoryEntry> committed_to_entry,
GC::Ref<WebIDL::Promise> committed_promise,
GC::Ref<WebIDL::Promise> finished_promise,
Pending pending)
: navigation(navigation)
, key(move(key))
, info(info)
, serialized_state(move(serialized_state))
, committed_to_entry(committed_to_entry)
, committed_promise(committed_promise)
, finished_promise(finished_promise)
, pending(pending)
{
}
void NavigationAPIMethodTracker::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(navigation);
visitor.visit(info);
visitor.visit(committed_to_entry);
visitor.visit(committed_promise);
visitor.visit(finished_promise);
}
GC::Ref<Navigation> Navigation::create(Window& window)
{
return GC::Heap::the().allocate<Navigation>(window);
}
Navigation::Navigation(Window& window)
: DOM::EventTarget()
, m_window(window)
{
}
Navigation::~Navigation() = default;
Window& Navigation::window() const
{
return m_window;
}
GC::Ptr<Bindings::Wrappable> Navigation::relevant_global_impl() const
{
return m_window;
}
void Navigation::visit_edges(JS::Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(m_entry_list);
visitor.visit(m_transition);
visitor.visit(m_activation);
visitor.visit(m_ongoing_navigate_event);
visitor.visit(m_window);
visitor.visit(m_ongoing_api_method_tracker);
visitor.visit(m_upcoming_traverse_api_method_trackers);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-entries
ReadonlySpan<GC::Ref<NavigationHistoryEntry>> Navigation::entries() const
{
// The entries() method steps are:
// 1. If this has entries and events disabled, then return the empty list.
if (has_entries_and_events_disabled())
return {};
// 2. Return this's entry list.
// NOTE: Recall that because of Web IDL's sequence type conversion rules,
// this will create a new JavaScript array object on each call.
// That is, navigation.entries() !== navigation.entries().
return m_entry_list;
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-current-entry
GC::Ptr<NavigationHistoryEntry> Navigation::current_entry() const
{
// The current entry of a Navigation navigation is the result of running the following steps:
// 1. If navigation has entries and events disabled, then return null.
if (has_entries_and_events_disabled())
return nullptr;
// 2. Assert: navigation's current entry index is not −1.
VERIFY(m_current_entry_index != -1);
// 3. Return navigation's entry list[navigation's current entry index].
return m_entry_list[m_current_entry_index];
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-updatecurrententry
WebIDL::ExceptionOr<void> Navigation::update_current_entry(NavigationUpdateCurrentEntryOptions options)
{
// The updateCurrentEntry(options) method steps are:
// 1. Let current be the current entry of this.
auto current = current_entry();
// 2. If current is null, then throw an "InvalidStateError" DOMException.
if (current == nullptr)
return WebIDL::InvalidStateError::create("Cannot update current NavigationHistoryEntry when there is no current entry"_utf16);
// 3. Let serializedState be StructuredSerializeForStorage(options["state"]), rethrowing any exceptions.
auto serialized_state = TRY(structured_serialize_session_history_state(window().principal_realm().vm(), options.state));
// 4. Set current's session history entry's navigation API state to serializedState.
current->session_history_entry().set_navigation_api_state(serialized_state);
// NB: Canonical session history needs to observe updateCurrentEntry() state changes so replacement WebContent processes
// can reconstruct Navigation API state.
auto& document = window().associated_document();
report_navigation_api_state_update(document, current->session_history_entry());
// 5. Fire an event named currententrychange at this using NavigationCurrentEntryChangeEvent,
// with its navigationType attribute initialized to null and its from initialized to current.
NavigationCurrentEntryChangeEventInit event_init { {}, *current, {} };
dispatch_event(HTML::NavigationCurrentEntryChangeEvent::create(HTML::EventNames::currententrychange, event_init, HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(window()))));
return {};
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-cangoback
bool Navigation::can_go_back() const
{
// The canGoBack getter steps are:
// 1. If this has entries and events disabled, then return false.
if (has_entries_and_events_disabled())
return false;
// 2. Assert: navigation's current entry index is not −1.
VERIFY(m_current_entry_index != -1);
// 3. If this's current entry index is 0, then return false.
// 4. Return true.
return (m_current_entry_index != 0);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-cangoforward
bool Navigation::can_go_forward() const
{
// The canGoForward getter steps are:
// 1. If this has entries and events disabled, then return false.
if (has_entries_and_events_disabled())
return false;
// 2. Assert: navigation's current entry index is not −1.
VERIFY(m_current_entry_index != -1);
// 3. If this's current entry index is equal to this's entry list's size − 1, then return false.
// 4. Return true.
return (m_current_entry_index != static_cast<i64>(m_entry_list.size() - 1));
}
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#history-handling-behavior
HistoryHandlingBehavior to_history_handling_behavior(NavigationHistoryBehavior b)
{
// A history handling behavior is a NavigationHistoryBehavior that is either "push" or "replace",
// i.e., that has been resolved away from any initial "auto" value.
VERIFY(b != NavigationHistoryBehavior::Auto);
switch (b) {
case NavigationHistoryBehavior::Push:
return HistoryHandlingBehavior::Push;
case NavigationHistoryBehavior::Replace:
return HistoryHandlingBehavior::Replace;
case NavigationHistoryBehavior::Auto:
VERIFY_NOT_REACHED();
};
VERIFY_NOT_REACHED();
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-navigate
WebIDL::ExceptionOr<NavigationResult> Navigation::navigate(Utf16String url, Bindings::NavigationNavigateOptions const& options)
{
auto& realm = window().principal_realm();
// The navigate(options) method steps are:
// 1. Let urlRecord be the result of parsing a URL given url, relative to this's relevant settings object.
auto url_record = window().relevant_settings_object().parse_url(url.utf16_view());
// 2. If urlRecord is failure, then return an early error result for a "SyntaxError" DOMException.
if (!url_record.has_value())
return early_error_result(WebIDL::SyntaxError::create("Cannot navigate to Invalid URL"_utf16));
// 3. If urlRecord's scheme is "javascript", then return an early error result for a "NotSupportedError" DOMException.
if (url_record->scheme() == "javascript"sv)
return early_error_result(WebIDL::NotSupportedError::create("Cannot navigate to a javascript: URL"_utf16));
// 4. Let document be this's relevant global object's associated Document.
auto& document = window().associated_document();
// 5. If options["history"] is "push", and the navigation must be a replace given urlRecord and document,
// then return an early error result for a "NotSupportedError" DOMException.
if (options.history == NavigationHistoryBehavior::Push && navigation_must_be_a_replace(url_record.value(), document))
return early_error_result(WebIDL::NotSupportedError::create("Navigation must be a replace, but push was requested"_utf16));
// 6. Let state be options["state"], if it exists; otherwise, undefined.
auto state = options.state.value_or(JS::js_undefined());
// 7. Let serializedState be StructuredSerializeForStorage(state). If this throws an exception, then return an early
// error result for that exception.
// NOTE: It is important to perform this step early, since serialization can invoke web developer code, which in
// turn might change various things we check in later steps.
auto serialized_state_or_error = structured_serialize_session_history_state(realm.vm(), state);
if (serialized_state_or_error.is_error()) {
return early_error_result(serialized_state_or_error.release_error());
}
auto serialized_state = serialized_state_or_error.release_value();
// 8. If document is not fully active, then return an early error result for an "InvalidStateError" DOMException.
if (!document.is_fully_active())
return early_error_result(WebIDL::InvalidStateError::create("Document is not fully active"_utf16));
// 9. If document's unload counter is greater than 0, then return an early error result for an "InvalidStateError" DOMException.
if (document.unload_counter() > 0)
return early_error_result(WebIDL::InvalidStateError::create("Document already unloaded"_utf16));
// AD-HOC: navigate() ignores this navigation, which would leave the promises unsettled.
if (document.navigable()->is_too_deeply_nested_to_load(*url_record))
return early_error_result(WebIDL::AbortError::create("Frame is nested too deeply"_utf16));
// 10. Let info be options["info"], if it exists; otherwise, undefined.
auto info = options.info.value_or(JS::js_undefined());
// 11. Let apiMethodTracker be the result of setting up a navigate/reload API method tracker for this given info
// and serializedState.
auto api_method_tracker = set_up_a_navigate_reload_api_method_tracker(info, serialized_state);
// 12. Navigate document's node navigable to urlRecord using document, with historyHandling set to
// options["history"], navigationAPIState set to serializedState, and apiMethodTracker set to apiMethodTracker.
// NOTE: Unlike location.assign() and friends, which are exposed across origin-domain boundaries,
// navigation.navigate() can only be accessed by code with direct synchronous access to the
// window.navigation property. Thus, we avoid the complications about attributing the source document
// of the navigation, and we don't need to deal with the allowed by sandboxing to navigate check and its
// acccompanying exceptionsEnabled flag. We just treat all navigations as if they come from the Document
// corresponding to this Navigation object itself (i.e., document).
TRY(document.navigable()->navigate({ .url = url_record.release_value(), .source_document = document, .history_handling = options.history, .navigation_api_state = move(serialized_state), .api_method_tracker = api_method_tracker }));
// 13. Return a navigation API method tracker-derived result for apiMethodTracker.
return navigation_api_method_tracker_derived_result(api_method_tracker);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-reload
WebIDL::ExceptionOr<NavigationResult> Navigation::reload(NavigationReloadOptions const& options)
{
return reload_internal(options);
}
WebIDL::ExceptionOr<NavigationResult> Navigation::reload_internal(NavigationReloadOptions const& options)
{
auto& realm = window().principal_realm();
// The reload(options) method steps are:
// 1. Let document be this's relevant global object's associated Document.
auto& document = window().associated_document();
// 2. Let serializedState be StructuredSerializeForStorage(undefined).
auto serialized_state = MUST(structured_serialize_for_storage(realm.vm(), JS::js_undefined()));
// 3. If options["state"] exists, then set serializedState to StructuredSerializeForStorage(options["state"]). If
// this throws an exception, then return an early error result for that exception.
// NOTE: It is important to perform this step early, since serialization can invoke web developer code, which in
// turn might change various things we check in later steps.
if (options.state.has_value()) {
auto serialized_state_or_error = structured_serialize_session_history_state(realm.vm(), *options.state);
if (serialized_state_or_error.is_error())
return early_error_result(serialized_state_or_error.release_error());
serialized_state = serialized_state_or_error.release_value();
}
// 4. Otherwise:
else {
// 1. Let current be the current entry of this.
auto current = current_entry();
// 2. If current is not null, then set serializedState to current's session history entry's navigation API state.
if (current != nullptr)
serialized_state = current->session_history_entry().navigation_api_state();
}
// 5. If document is not fully active, then return an early error result for an "InvalidStateError" DOMException.
if (!document.is_fully_active())
return early_error_result(WebIDL::InvalidStateError::create("Document is not fully active"_utf16));
// 6. If document's unload counter is greater than 0, then return an early error result for an "InvalidStateError" DOMException.
if (document.unload_counter() > 0)
return early_error_result(WebIDL::InvalidStateError::create("Document already unloaded"_utf16));
// 7. Let info be options["info"], if it exists; otherwise, undefined.
auto info = options.info.value_or(JS::js_undefined());
// 8. Let apiMethodTracker be the result of setting up a navigate/reload API method tracker for this given info
// and serializedState.
auto api_method_tracker = set_up_a_navigate_reload_api_method_tracker(info, serialized_state);
// 9. Reload document's node navigable with navigationAPIState set to serializedState and apiMethodTracker set to
// apiMethodTracker.
document.navigable()->reload(move(serialized_state), UserNavigationInvolvement::None, api_method_tracker);
// 10. Return a navigation API method tracker-derived result for apiMethodTracker.
return navigation_api_method_tracker_derived_result(api_method_tracker);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-traverseto
WebIDL::ExceptionOr<NavigationResult> Navigation::traverse_to(Utf16String key, Bindings::NavigationOptions const& options)
{
// The traverseTo(key, options) method steps are:
// 1. If this's current entry index is −1, then return an early error result for an "InvalidStateError" DOMException.
if (m_current_entry_index == -1)
return early_error_result(WebIDL::InvalidStateError::create("Cannot traverseTo: no current session history entry"_utf16));
// 2. If this's entry list does not contain a NavigationHistoryEntry whose session history entry's navigation API key equals key,
// then return an early error result for an "InvalidStateError" DOMException.
auto it = m_entry_list.find_if([&key](auto const& entry) {
return entry->session_history_entry().navigation_api_key() == key;
});
if (it == m_entry_list.end())
return early_error_result(WebIDL::InvalidStateError::create("Cannot traverseTo: key not found in session history list"_utf16));
// 3. Return the result of performing a navigation API traversal given this, key, and options.
return perform_a_navigation_api_traversal(key, options);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#performing-a-navigation-api-traversal
WebIDL::ExceptionOr<NavigationResult> Navigation::back(NavigationOptions const& options)
{
return back_internal(options);
}
WebIDL::ExceptionOr<NavigationResult> Navigation::back_internal(NavigationOptions const& options)
{
// The back(options) method steps are:
// 1. If this's current entry index is −1 or 0, then return an early error result for an "InvalidStateError" DOMException.
if (m_current_entry_index == -1 || m_current_entry_index == 0)
return early_error_result(WebIDL::InvalidStateError::create("Cannot navigate back: no previous session history entry"_utf16));
// 2. Let key be this's entry list[this's current entry index − 1]'s session history entry's navigation API key.
auto key = m_entry_list[m_current_entry_index - 1]->session_history_entry().navigation_api_key();
// 3. Return the result of performing a navigation API traversal given this, key, and options.
return perform_a_navigation_api_traversal(key, options);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-forward
WebIDL::ExceptionOr<NavigationResult> Navigation::forward(NavigationOptions const& options)
{
return forward_internal(options);
}
WebIDL::ExceptionOr<NavigationResult> Navigation::forward_internal(NavigationOptions const& options)
{
// The forward(options) method steps are:
// 1. If this's current entry index is −1 or is equal to this's entry list's size − 1,
// then return an early error result for an "InvalidStateError" DOMException.
if (m_current_entry_index == -1 || m_current_entry_index == static_cast<i64>(m_entry_list.size() - 1))
return early_error_result(WebIDL::InvalidStateError::create("Cannot navigate forward: no next session history entry"_utf16));
// 2. Let key be this's entry list[this's current entry index + 1]'s session history entry's navigation API key.
auto key = m_entry_list[m_current_entry_index + 1]->session_history_entry().navigation_api_key();
// 3. Return the result of performing a navigation API traversal given this, key, and options.
return perform_a_navigation_api_traversal(key, options);
}
void Navigation::set_onnavigate(WebIDL::CallbackType* event_handler)
{
set_event_handler_attribute(HTML::EventNames::navigate, event_handler);
}
WebIDL::CallbackType* Navigation::onnavigate()
{
return event_handler_attribute(HTML::EventNames::navigate);
}
void Navigation::set_onnavigatesuccess(WebIDL::CallbackType* event_handler)
{
set_event_handler_attribute(HTML::EventNames::navigatesuccess, event_handler);
}
WebIDL::CallbackType* Navigation::onnavigatesuccess()
{
return event_handler_attribute(HTML::EventNames::navigatesuccess);
}
void Navigation::set_onnavigateerror(WebIDL::CallbackType* event_handler)
{
set_event_handler_attribute(HTML::EventNames::navigateerror, event_handler);
}
WebIDL::CallbackType* Navigation::onnavigateerror()
{
return event_handler_attribute(HTML::EventNames::navigateerror);
}
void Navigation::set_oncurrententrychange(WebIDL::CallbackType* event_handler)
{
set_event_handler_attribute(HTML::EventNames::currententrychange, event_handler);
}
WebIDL::CallbackType* Navigation::oncurrententrychange()
{
return event_handler_attribute(HTML::EventNames::currententrychange);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#has-entries-and-events-disabled
bool Navigation::has_entries_and_events_disabled() const
{
// A Navigation navigation has entries and events disabled if the following steps return true:
// 1. Let document be navigation's relevant global object's associated Document.
auto const& document = window().associated_document();
// 2. If document is not fully active, then return true.
if (!document.is_fully_active())
return true;
// 3. If document's is initial about:blank is true, then return true.
if (document.is_initial_about_blank())
return true;
// 4. If document's origin is opaque, then return true.
if (document.origin().is_opaque())
return true;
// AD-HOC: Keep entries and events disabled when document.open() is called on an initial about:blank document. This
// behavior matches other engines.
// Spec issue: https://github.com/whatwg/html/issues/11811
if (m_was_initial_about_blank_opened)
return true;
// 5. Return false.
return false;
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#getting-the-navigation-api-entry-index
i64 Navigation::get_the_navigation_api_entry_index(SessionHistoryEntry const& she) const
{
// To get the navigation API entry index of a session history entry she within a Navigation navigation:
// 1. Let index be 0.
i64 index = 0;
// 2. For each nhe of navigation's entry list:
for (auto const& nhe : m_entry_list) {
// 1. If nhe's session history entry is equal to she, then return index.
if (&nhe->session_history_entry() == &she)
return index;
// 2. Increment index by 1.
++index;
}
// 3. Return −1.
return -1;
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-api-early-error-result
NavigationResult Navigation::early_error_result(AnyException e)
{
auto& settings_object = window().relevant_settings_object();
// An early error result for an exception e is a NavigationResult dictionary instance given by
// «[ "committed" → a promise rejected with e, "finished" → a promise rejected with e ]».
return NavigationResult::from_promises(
WebIDL::create_rejected_promise_from_exception_for(settings_object, e),
WebIDL::create_rejected_promise_from_exception_for(settings_object, e));
}
NavigationResult Navigation::early_error_result(GC::Ref<WebIDL::DOMException> exception)
{
auto& settings_object = window().relevant_settings_object();
return NavigationResult::from_promises(
WebIDL::create_rejected_promise_for(settings_object, exception),
WebIDL::create_rejected_promise_for(settings_object, exception));
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-api-method-tracker-derived-result
NavigationResult Navigation::navigation_api_method_tracker_derived_result(GC::Ref<NavigationAPIMethodTracker> api_method_tracker)
{
// To compute the navigation API method tracker-derived result for a navigation API method tracker-or-null
// apiMethodTracker:
// 1. If apiMethodTracker is pending, then return an early error result for an "AbortError" DOMException.
if (api_method_tracker->pending == NavigationAPIMethodTracker::Pending::Yes)
return early_error_result(WebIDL::AbortError::create("Navigation aborted"_utf16));
// 2. Return a NavigationResult dictionary instance given by «[ "committed" → apiMethodTracker's committed
// promise, "finished" → apiMethodTracker's finished promise ]».
return NavigationResult::from_promises(api_method_tracker->committed_promise, api_method_tracker->finished_promise);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#set-up-a-navigate/reload-api-method-tracker
GC::Ref<NavigationAPIMethodTracker> Navigation::set_up_a_navigate_reload_api_method_tracker(JS::Value info, Optional<StorageSerializationRecord> serialized_state)
{
// To set up a navigate/reload API method tracker given a Navigation navigation, a JavaScript value info, and a
// serialized state-or-null serializedState:
// 1. Let committedPromise and finishedPromise be new promises created in navigation's relevant realm.
auto committed_promise = WebIDL::create_promise_for(window());
auto finished_promise = WebIDL::create_promise_for(window());
// 2. Mark as handled finishedPromise.
// NOTE: The web developer doesn’t necessarily care about finishedPromise being rejected:
// - They might only care about committedPromise.
// - They could be doing multiple synchronous navigations within the same task,
// in which case all but the last will be aborted (causing their finishedPromise to reject).
// This could be an application bug, but also could just be an emergent feature of disparate
// parts of the application overriding each others' actions.
// - They might prefer to listen to other transition-failure signals instead of finishedPromise, e.g.,
// the navigateerror event, or the navigation.transition.finished promise.
// As such, we mark it as handled to ensure that it never triggers unhandledrejection events.
WebIDL::mark_promise_as_handled(finished_promise);
// 3. Return a new navigation API method tracker with:
// navigation object: navigation
// key: null
// info: info
// serialized state: serializedState
// committed-to entry: null
// committed promise: committedPromise
// finished promise: finishedPromise
// pending: false if navigation has entries and events disabled; otherwise true
return GC::Heap::the().allocate<NavigationAPIMethodTracker>(
/* .navigation = */ *this,
/* .key = */ OptionalNone {},
/* .info = */ info,
/* .serialized_state = */ move(serialized_state),
/* .committed_to_entry = */ nullptr,
/* .committed_promise = */ committed_promise,
/* .finished_promise = */ finished_promise,
/* .pending = */ has_entries_and_events_disabled() ? NavigationAPIMethodTracker::Pending::No : NavigationAPIMethodTracker::Pending::Yes);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#add-an-upcoming-traverse-api-method-tracker
GC::Ref<NavigationAPIMethodTracker> Navigation::add_an_upcoming_traverse_api_method_tracker(Utf16String destination_key, JS::Value info)
{
// To add an upcoming traverse API method tracker given a Navigation navigation, a string destinationKey, and a JavaScript value info:
// 1. Let committedPromise and finishedPromise be new promises created in navigation's relevant realm.
auto committed_promise = WebIDL::create_promise_for(window());
auto finished_promise = WebIDL::create_promise_for(window());
// 2. Mark as handled finishedPromise.
// NOTE: See the previous discussion about why this is done
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#note-mark-as-handled-navigation-api-finished
WebIDL::mark_promise_as_handled(*finished_promise);
// 3. Let apiMethodTracker be a new navigation API method tracker with:
// navigation object: navigation
// key: destinationKey
// info: info
// serialized state: null
// committed-to entry: null
// committed promise: committedPromise
// finished promise: finishedPromise
// pending: false
auto api_method_tracker = GC::Heap::the().allocate<NavigationAPIMethodTracker>(
/* .navigation = */ *this,
/* .key = */ destination_key,
/* .info = */ info,
/* .serialized_state = */ OptionalNone {},
/* .committed_to_entry = */ nullptr,
/* .committed_promise = */ committed_promise,
/* .finished_promise = */ finished_promise,
/* .pending = */ NavigationAPIMethodTracker::Pending::No);
// 4. Set navigation's upcoming traverse API method trackers[destinationKey] to apiMethodTracker.
m_upcoming_traverse_api_method_trackers.set(destination_key, api_method_tracker);
// 5. Return apiMethodTracker.
return api_method_tracker;
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#performing-a-navigation-api-traversal
WebIDL::ExceptionOr<NavigationResult> Navigation::perform_a_navigation_api_traversal(Utf16String key, Bindings::NavigationOptions const& options)
{
// To perform a navigation API traversal given a Navigation navigation, a string key, and a NavigationOptions options:
// 1. Let document be this's relevant global object's associated Document.
auto& document = window().associated_document();
// 2. If document is not fully active, then return an early error result for an "InvalidStateError" DOMException.
if (!document.is_fully_active())
return early_error_result(WebIDL::InvalidStateError::create("Document is not fully active"_utf16));
// 3. If document's unload counter is greater than 0, then return an early error result for an "InvalidStateError" DOMException.
if (document.unload_counter() > 0)
return early_error_result(WebIDL::InvalidStateError::create("Document already unloaded"_utf16));
// 4. Let current be the current entry of navigation.
auto current = current_entry();
// 5. If key equals current's session history entry's navigation API key, then return
// «[ "committed" → a promise resolved with current, "finished" → a promise resolved with current ]».
if (key == current->session_history_entry().navigation_api_key())
return NavigationResult::resolved_with_entry(current.as_nonnull());
// 6. If navigation's upcoming traverse API method trackers[key] exists,
// then return a navigation API method tracker-derived result for navigation's upcoming traverse API method trackers[key].
if (auto maybe_tracker = m_upcoming_traverse_api_method_trackers.get(key); maybe_tracker.has_value())
return navigation_api_method_tracker_derived_result(maybe_tracker.value());
// 7. Let info be options["info"], if it exists; otherwise, undefined.
auto info = options.info.value_or(JS::js_undefined());
// 8. Let apiMethodTracker be the result of adding an upcoming traverse API method tracker for navigation given key and info.
auto api_method_tracker = add_an_upcoming_traverse_api_method_tracker(key, info);
// 9. Let navigable be document's node navigable.
auto navigable = document.navigable();
// 10. Let traversable be navigable's traversable navigable.
// 11. Let sourceSnapshotParams be the result of snapshotting source snapshot params given document.
auto source_snapshot_params = snapshot_source_snapshot_params(document);
// 12. Append the following session history traversal steps to traversable:
// NB: The UI process runs these steps. This process rejects apiMethodTracker's finished promise when they say to.
// 2-3. If there is no targetSHE, or it is navigable's active session history entry:
// 1. Queue a global task on the navigation and traversal task source given navigation's relevant global object
// to reject the finished promise for apiMethodTracker with an "InvalidStateError" DOMException.
// 2. Abort these steps.
// NOTE: The target-missing path is taken if navigation's entry list was outdated compared to navigableSHEs,
// which can occur for brief periods while all the relevant threads and processes are being synchronized
// in reaction to a history change.
auto on_rejected = GC::create_function(heap(), GC::captures(*this, api_method_tracker), [](auto& self, auto& api_method_tracker) {
queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(self.window()), GC::create_function(self.heap(), GC::captures(self, api_method_tracker), [](auto& self, auto& api_method_tracker) {
auto& realm = relevant_realm(self.window());
TemporaryExecutionContext execution_context { realm };
self.reject_the_finished_promise(api_method_tracker,
WebIDL::InvalidStateError::create(realm, "Cannot traverse with stale session history entry"_utf16));
}));
});
auto on_apply_history_step_complete = GC::create_function<void(HistoryStepResult)>(heap(), GC::captures(*this, api_method_tracker), [](auto& self, auto& api_method_tracker, HistoryStepResult result) {
// NOTE: When result is "canceled-by-beforeunload" or "initiator-disallowed", the navigate event was never fired,
// aborting the ongoing navigation would not be correct; it would result in a navigateerror event without a
// preceding navigate event. In the "canceled-by-navigate" case, navigate is fired, but the inner navigate event
// firing algorithm will take care of aborting the ongoing navigation.
auto& realm = relevant_realm(self.window());
auto& global = relevant_global_object(self.window());
// 5. If result is "canceled-by-beforeunload", then queue a global task on the navigation and traversal task source
// given navigation's relevant global object to reject the finished promise for apiMethodTracker with a
// new "AbortError" DOMException created in navigation's relevant realm.
if (result == HistoryStepResult::CanceledByBeforeUnload) {
queue_global_task(Task::Source::NavigationAndTraversal, global, GC::create_function(self.heap(), GC::captures(self, api_method_tracker, realm), [](auto& self, auto& api_method_tracker, auto& realm) {
TemporaryExecutionContext execution_context { realm };
self.reject_the_finished_promise(api_method_tracker, WebIDL::AbortError::create(realm, "Navigation cancelled by beforeunload"_utf16));
}));
}
// 6. If result is "initiator-disallowed", then queue a global task on the navigation and traversal task source
// given navigation's relevant global object to reject the finished promise for apiMethodTracker with a
// new "SecurityError" DOMException created in navigation's relevant realm.
if (result == HistoryStepResult::InitiatorDisallowed) {
queue_global_task(Task::Source::NavigationAndTraversal, global, GC::create_function(self.heap(), GC::captures(self, api_method_tracker, realm), [](auto& self, auto& api_method_tracker, auto& realm) {
TemporaryExecutionContext execution_context { realm };
self.reject_the_finished_promise(api_method_tracker, WebIDL::SecurityError::create(realm, "Navigation disallowed from this origin"_utf16));
}));
}
});
// 4. Let result be the result of applying the traverse history step given by targetSHE's step to traversable,
// given sourceSnapshotParams, navigable, and "none".
navigable->page().history_executor().request_history_operation(
NavigationAPITraverseHistoryOperationParameters {
.navigable_id = navigable->id(),
.key = key,
.source_snapshot_params = create_navigation_source_snapshot(*source_snapshot_params),
.user_involvement = UserNavigationInvolvement::None,
},
{
.on_apply_history_step_complete = on_apply_history_step_complete,
.on_navigation_api_traversal_rejected = on_rejected,
});
// 13. Return a navigation API method tracker-derived result for apiMethodTracker.
return navigation_api_method_tracker_derived_result(api_method_tracker);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#abort-the-ongoing-navigation
void Navigation::abort_the_ongoing_navigation(GC::Ptr<WebIDL::DOMException> error)
{
// To abort the ongoing navigation given a Navigation navigation and an optional DOMException error:
// 1. Let event be navigation's ongoing navigate event.
auto event = ongoing_navigate_event();
// 2. Assert: event is not null.
VERIFY(event != nullptr);
// 3. Set navigation's focus changed during ongoing navigation to false.
m_focus_changed_during_ongoing_navigation = false;
// 4. Set navigation's suppress normal scroll restoration during ongoing navigation to false.
m_suppress_normal_scroll_restoration_during_ongoing_navigation = false;
// 5. If error was not given, then let error be a new "AbortError" DOMException created in navigation's relevant realm.
if (!error)
error = WebIDL::AbortError::create("Navigation aborted"_utf16);
VERIFY(error);
// 6. If event's dispatch flag is set, then set event's canceled flag to true.
if (event->dispatched())
event->set_cancelled(true);
// 7. Abort event given error.
abort_a_navigate_event(*event, *error);
}
void Navigation::abort_a_navigate_event(GC::Ref<NavigateEvent> event, GC::Ref<WebIDL::DOMException> reason)
{
abort_a_navigate_event(event, throw_completion(window().principal_realm(), reason).value());
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#abort-a-navigateevent
void Navigation::abort_a_navigate_event(GC::Ref<NavigateEvent> event, JS::Value reason_value)
{
auto& realm = window().principal_realm();
// 1. Let navigation be event's relevant global object's navigation API.
// NB: Navigation is `this`.
// AD-HOC: Aborting can be triggered from session history traversal tasks with no JavaScript on the stack, and
// both the abort signal and the promise rejections below run script.
TemporaryExecutionContext execution_context { window().principal_realm(), TemporaryExecutionContext::CallbacksEnabled::Yes };
// 2. Set navigation's ongoing navigate event to null.
m_ongoing_navigate_event = nullptr;
// AD-HOC: An aborted intercepted traverse must not be resumed. See https://github.com/whatwg/html/issues/12362.
if (auto operation_id = event->resume_traversal_operation_id(); operation_id.has_value())
window().page().history_executor().revoke_history_operation(*operation_id);
// 5. If navigation's ongoing API method tracker is non-null, then reject the finished promise for apiMethodTracker
// with reason.
// AD-HOC: This runs before signaling abort, since an abort handler can start a new navigation. Its inner navigate
// event firing algorithm asserts that no API method tracker is ongoing, and leaving this one in place would
// reject the new navigation's tracker instead.
if (m_ongoing_api_method_tracker)
reject_the_finished_promise(*m_ongoing_api_method_tracker, reason_value);
// 3. Signal abort on event's abort controller given reason.
event->abort_controller()->abort(realm, reason_value);
// 4. Let errorInfo be the result of extracting error information from reason.
auto error_info = extract_error_information(vm(), reason_value);
// 6. Fire an event named navigateerror at navigation using ErrorEvent, with additional attributes initialized
// according to errorInfo.
ErrorEventInit event_init = {};
event_init.filename = error_info.filename;
event_init.message = error_info.message;
event_init.lineno = error_info.lineno;
event_init.colno = error_info.colno;
event_init.error = error_info.error;
dispatch_event(ErrorEvent::create(EventNames::navigateerror, event_init, HighResolutionTime::current_high_resolution_time(realm.global_object())));
// 7. If navigation's transition is null, then return.
if (!m_transition)
return;
// 8. Reject navigation's transition's committed promise with reason.
WebIDL::reject_promise(m_transition->committed(), reason_value);
// 9. Reject navigation's transition's finished promise with reason.
WebIDL::reject_promise(m_transition->finished(), reason_value);
// 10. Set navigation's transition to null.
m_transition = nullptr;
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-api-method-tracker-clean-up
void Navigation::clean_up(GC::Ref<NavigationAPIMethodTracker> api_method_tracker)
{
// 1. Let navigation be apiMethodTracker's navigation object.
VERIFY(api_method_tracker->navigation.ptr() == this);
// 2. If navigation's ongoing API method tracker is apiMethodTracker, then set navigation's ongoing API method tracker to null.
if (m_ongoing_api_method_tracker == api_method_tracker) {
m_ongoing_api_method_tracker = nullptr;
}
// 3. Otherwise:
else {
// 1. Let key be apiMethodTracker's key.
auto& key = api_method_tracker->key;
// 2. Assert: key is not null.
VERIFY(key.has_value());
// 3. Assert: navigation's upcoming traverse API method trackers[key] exists.
VERIFY(m_upcoming_traverse_api_method_trackers.contains(*key));
// 4. Remove navigation's upcoming traverse API method trackers[key].
m_upcoming_traverse_api_method_trackers.remove(*key);
}
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#reject-the-finished-promise
void Navigation::reject_the_finished_promise(GC::Ref<NavigationAPIMethodTracker> api_method_tracker, JS::Value exception)
{
// 1. Reject apiMethodTracker's committed promise with exception.
// NOTE: This will do nothing if apiMethodTracker's committed promise was previously resolved
// via notify about the committed-to entry.
WebIDL::reject_promise(api_method_tracker->committed_promise, exception);
// 2. Reject apiMethodTracker's finished promise with exception.
WebIDL::reject_promise(api_method_tracker->finished_promise, exception);
// 3. Clean up apiMethodTracker.
clean_up(api_method_tracker);
}
void Navigation::reject_the_finished_promise(GC::Ref<NavigationAPIMethodTracker> api_method_tracker, GC::Ref<WebIDL::DOMException> exception)
{
reject_the_finished_promise(api_method_tracker, throw_completion(window().principal_realm(), exception).value());
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#resolve-the-finished-promise
void Navigation::resolve_the_finished_promise(GC::Ref<NavigationAPIMethodTracker> api_method_tracker)
{
auto& realm = window().principal_realm();
// 1. Assert: apiMethodTracker's committed-to entry is not null.
VERIFY(api_method_tracker->committed_to_entry != nullptr);
// 2. Resolve apiMethodTracker's finished promise with its committed-to entry.
resolve_navigation_history_entry_promise(realm, api_method_tracker->finished_promise, GC::Ref { *api_method_tracker->committed_to_entry });
// 3. Clean up apiMethodTracker.
clean_up(api_method_tracker);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#notify-about-the-committed-to-entry
void Navigation::notify_about_the_committed_to_entry(GC::Ref<NavigationAPIMethodTracker> api_method_tracker, GC::Ref<NavigationHistoryEntry> nhe)
{
auto& realm = window().principal_realm();
// 1. Set apiMethodTracker's committed-to entry to nhe.
api_method_tracker->committed_to_entry = nhe;
// 2. If apiMethodTracker's serialized state is not null, then set nhe's session history entry's navigation API state to apiMethodTracker's serialized state.'
// NOTE: If it's null, then we're traversing to nhe via navigation.traverseTo(), which does not allow changing the state.
if (api_method_tracker->serialized_state.has_value()) {
// NOTE: At this point, apiMethodTracker's serialized state is no longer needed.
// Implementations might want to clear it out to avoid keeping it alive for the lifetime of the navigation API method tracker.
nhe->session_history_entry().set_navigation_api_state(*api_method_tracker->serialized_state);
api_method_tracker->serialized_state = {};
}
// 3. Resolve apiMethodTracker's committed promise with nhe.
TemporaryExecutionContext execution_context { realm };
resolve_navigation_history_entry_promise(realm, api_method_tracker->committed_promise, nhe);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigate-event-intercept-commit-handler-steps
void Navigation::run_the_navigate_event_intercept_commit_handler_steps(GC::Ref<NavigateEvent> event, GC::Ptr<NavigationAPIMethodTracker> api_method_tracker)
{
VERIFY(!event->has_started_navigate_event_intercept_commit_handler_steps());
event->set_has_started_navigate_event_intercept_commit_handler_steps();
auto& realm = window().principal_realm();
// 1. Let promisesList be an empty list.
GC::RootVector<GC::Ref<WebIDL::Promise>> promises_list;
// 2. For each handler of event's navigation handler list:
for (auto const& handler : event->navigation_handler_list()) {
// 1. Append the result of invoking handler with an empty arguments list to promisesList.
promises_list.append(invoke_navigation_intercept_handler(handler));
}
// 3. If promisesList's size is 0, then set promisesList to « a promise resolved with undefined ».
// NOTE: There is a subtle timing difference between how waiting for all schedules its success and failure
// steps when given zero promises versus ≥1 promises. For most uses of waiting for all, this does not matter.
// However, with this API, there are so many events and promise handlers which could fire around the same time
// that the difference is pretty easily observable: it can cause the event/promise handler sequence to vary.
// (Some of the events and promises involved include: navigatesuccess / navigateerror, currententrychange,
// dispose, apiMethodTracker's promises, and the navigation.transition.finished promise.)
if (promises_list.size() == 0) {
promises_list.append(WebIDL::create_resolved_promise_for(window(), JS::js_undefined()));
}
// 4. Wait for all of promisesList, with the following success steps:
WebIDL::wait_for_all(
realm, promises_list, GC::create_function(GC::Heap::the(), GC::captures(event, *this, api_method_tracker), [](auto& event, auto& self, auto& api_method_tracker, Vector<JS::Value> const&) {
// 1. If event's relevant global object is not fully active, then abort these steps.
auto& window = event->relevant_window();
if (!window.associated_document().is_fully_active())
return;
// 2. If event's abort controller's signal is aborted, then abort these steps.
if (event->abort_controller()->signal()->aborted())
return;
// 3. Assert: event equals navigation's ongoing navigate event.
VERIFY(event == self.m_ongoing_navigate_event);
// 4. Set navigation's ongoing navigate event to null.
self.m_ongoing_navigate_event = nullptr;
// 6. If apiMethodTracker is non-null, then resolve the finished promise for apiMethodTracker.
// AD-HOC: This runs before finishing the event, since resetting the focus can start a new navigation
// from a blur handler, and its inner navigate event firing algorithm asserts that no API method
// tracker is ongoing.
if (api_method_tracker != nullptr)
self.resolve_the_finished_promise(*api_method_tracker);
// 5. Finish event given true.
event->finish(true);
// FIXME: Implement https://dom.spec.whatwg.org/#concept-event-fire somewhere
// 7. Fire an event named navigatesuccess at navigation.
self.dispatch_event(DOM::Event::create(
EventNames::navigatesuccess,
HighResolutionTime::current_high_resolution_time(relevant_global_object(window))));
// 8. If navigation's transition is not null, then resolve navigation's transition's finished promise with undefined.
if (self.m_transition != nullptr)
WebIDL::resolve_promise(self.m_transition->finished());
// 9. Set navigation's transition to null.
self.m_transition = nullptr; }),
// and the following failure step given reason: process navigate event handler failure given event and reason.
GC::create_function(GC::Heap::the(), GC::captures(event, *this), [](auto& event, auto& self, JS::Value reason) {
self.process_navigate_event_handler_failure(event, reason);
}));
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#process-navigate-event-handler-failure
void Navigation::process_navigate_event_handler_failure(GC::Ref<NavigateEvent> event, JS::Value reason)
{
// 1. If event's relevant global object's associated Document is not fully active, then return.
if (!event->relevant_window().associated_document().is_fully_active())
return;
// 2. If event's abort controller's signal is aborted, then return.
if (event->abort_controller()->signal()->aborted())
return;
// 3. Assert: event is event's relevant global object's navigation API's ongoing navigate event.
VERIFY(event == m_ongoing_navigate_event);
// AD-HOC: Settle the ongoing API method tracker before finishing the event, see the navigate event intercept
// commit handler steps.
if (m_ongoing_api_method_tracker)
reject_the_finished_promise(*m_ongoing_api_method_tracker, reason);
// 4. If event's interception state is not "intercepted", then finish event given false.
if (event->interception_state() != NavigateEvent::InterceptionState::Intercepted)
event->finish(false);
// 5. Abort event given reason.
abort_a_navigate_event(event, reason);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#inner-navigate-event-firing-algorithm
bool Navigation::inner_navigate_event_firing_algorithm(
NavigationType navigation_type,
GC::Ref<NavigationDestination> destination,
UserNavigationInvolvement user_involvement,
GC::Ptr<DOM::Element> source_element,
Optional<GC::RootVector<XHR::FormDataEntry>&> form_data_entry_list,
Optional<Utf16String> download_request_filename,
Optional<StorageSerializationRecord> classic_history_api_state,
GC::Ptr<NavigationAPIMethodTracker> api_method_tracker)
{
// NOTE: Specification assumes that ongoing navigation event is cancelled before dispatching next navigation event.
if (m_ongoing_navigate_event)
abort_the_ongoing_navigation();
auto& realm = window().principal_realm();
// 1. If navigation has entries and events disabled:
// NOTE: These assertions holds because traverseTo(), back(), and forward() will immediately fail when entries and
// events are disabled (since there are no entries to traverse to).
if (has_entries_and_events_disabled()) {
// 1. Assert: navigation's ongoing API method tracker is null.
VERIFY(m_ongoing_api_method_tracker == nullptr);
// 2. Assert: navigation's upcoming traverse API method trackers is empty.
VERIFY(m_upcoming_traverse_api_method_trackers.is_empty());
// 3. Assert: apiMethodTracker is null.
VERIFY(api_method_tracker == nullptr);
// 4. Return true.
return true;
}
// 2. Assert: navigation's ongoing API method tracker is null.
VERIFY(m_ongoing_api_method_tracker == nullptr);
// 3. If destination's entry is non-null:
if (destination->navigation_history_entry() != nullptr) {
// 1. Assert: apiMethodTracker is null.
// NOTE: apiMethodTracker is passed as an argument only for navigate() and reload() calls.
VERIFY(api_method_tracker == nullptr);
// 2. Let destinationKey be destination's entry's key.
auto destination_key = destination->navigation_history_entry()->key();
// 3. Assert: destinationKey is not the empty string.
VERIFY(!destination_key.is_empty());
// 4. If navigation's upcoming traverse API method trackers[destinationKey] exists:
if (auto tracker = m_upcoming_traverse_api_method_trackers.get(destination_key); tracker.has_value()) {
// 1. Set apiMethodTracker to navigation's upcoming traverse API method trackers[destinationKey].
api_method_tracker = tracker.value();
// 2. Remove navigation's upcoming traverse API method trackers[destinationKey].
m_upcoming_traverse_api_method_trackers.remove(destination_key);
}
}
// 4. If apiMethodTracker is not null:
if (api_method_tracker) {
// 1. Set navigation's ongoing API method tracker to apiMethodTracker.
m_ongoing_api_method_tracker = api_method_tracker;
// 2. Set apiMethodTracker's pending to false.
api_method_tracker->pending = NavigationAPIMethodTracker::Pending::No;
}
// 5. Let navigable be navigation's relevant global object's navigable.
auto& window = this->window();
auto navigable = window.navigable();
// 6. Let document be navigation's relevant global object's associated Document.
auto& document = window.associated_document();
// 17. Set event's abort controller to a new AbortController created in navigation's relevant realm.
// AD-HOC: Set on the NavigateEvent later after construction
auto abort_controller = DOM::AbortController::create();
// Note: We create the Event in this algorithm instead of passing it in,
// and have all the following "initialize" steps set up the event init
NavigateEventInit event_init {
{},
NavigationType::Push,
destination,
false,
false,
false,
abort_controller->signal(),
nullptr,
{},
{},
false,
nullptr,
};
// 7. If document can have its URL rewritten to destination's URL,
// and either destination's is same document is true or navigationType is not "traverse",
// then initialize event's canIntercept to true. Otherwise, initialize it to false.
event_init.can_intercept = can_have_its_url_rewritten(document, destination->raw_url()) && (destination->same_document() || navigation_type != NavigationType::Traverse);
// 8. Let traverseCanBeCanceled be true if all of the following are true:
// - navigable is a top-level traversable;
// - destination's is same document is true; and
// - either userInvolvement is not "browser UI", or navigation's relevant global object has history-action activation.
// Otherwise, let it be false.
bool const traverse_can_be_canceled = navigable->is_top_level_traversable()
&& destination->same_document()
&& (user_involvement != UserNavigationInvolvement::BrowserUI || window.has_history_action_activation());
// 9. If either:
// - navigationType is not "traverse"; or
// - traverseCanBeCanceled is true
// then initialize event's cancelable to true. Otherwise, initialize it to false.
event_init.cancelable = (navigation_type != NavigationType::Traverse) || traverse_can_be_canceled;
// 10. Initialize event's type to "navigate".
// AD-HOC: Happens later, when calling the factory function
// 11. Initialize event's navigationType to navigationType.
event_init.navigation_type = navigation_type;
// 12. Initialize event's destination to destination.
event_init.destination = destination;
// 13. Initialize event's downloadRequest to downloadRequestFilename.
event_init.download_request = move(download_request_filename);
// 14. If apiMethodTracker is not null, then initialize event's info to apiMethodTracker's info. Otherwise, initialize it to undefined.
// NOTE: At this point apiMethodTracker's info is no longer needed and can be nulled out instead of keeping it alive for the lifetime of the navigation API method tracker.
if (api_method_tracker) {
event_init.info = api_method_tracker->info;
api_method_tracker->info = JS::js_undefined();
} else {
event_init.info = JS::js_undefined();
}
// FIXME: 15. Initialize event's hasUAVisualTransition to true if a visual transition, to display a cached rendered state
// of the document's latest entry, was done by the user agent. Otherwise, initialize it to false.
event_init.has_ua_visual_transition = false;
// 16. Initialize event's sourceElement to sourceElement.
// AD-HOC: Do not expose an element from a cross-origin initiator to this document. All engines implement this.
// See https://github.com/whatwg/html/pull/13090
if (source_element && !source_element->document().origin().is_same_origin_domain(document.origin()))
source_element = nullptr;
event_init.source_element = source_element;
// 18. Initialize event's signal to event's abort controller's signal.
// AD-HOC: Done when event_init is created.
// 19. Let currentURL be document's URL.
auto current_url = document.url();
// 20. If all of the following are true:
// - event's classic history API state is null;
// - destination's is same document is true;
// - destination's URL equals currentURL with exclude fragments set to true; and
// - destination's URL's fragment is not identical to currentURL's fragment,
// then initialize event's hashChange to true. Otherwise, initialize it to false.
event_init.hash_change = (!classic_history_api_state.has_value()
&& destination->same_document()
&& destination->raw_url().equals(current_url, URL::ExcludeFragment::Yes)
&& destination->raw_url().fragment() != current_url.fragment());
// 21. If userInvolvement is not "none", then initialize event's userInitiated to true. Otherwise, initialize it to false.
event_init.user_initiated = user_involvement != UserNavigationInvolvement::None;
// 22. If formDataEntryList is not null, then initialize event's formData to a new FormData created in navigation's relevant realm,
// associated to formDataEntryList. Otherwise, initialize it to null.
if (form_data_entry_list.has_value()) {
event_init.form_data = XHR::FormData::create(form_data_entry_list.release_value());
} else {
event_init.form_data = nullptr;
}
// AD-HOC: *Now* we have all the info required to create the event
auto event = NavigateEvent::create(window, EventNames::navigate, event_init, HighResolutionTime::current_high_resolution_time(realm.global_object()));
event->set_abort_controller(abort_controller);
// AD-HOC: This is supposed to be set in "fire a <type> navigate event", and is only non-null when
// we're doing a push or replace. We set it here because we create the event here
event->set_classic_history_api_state(move(classic_history_api_state));
// 23. Assert: navigation's ongoing navigate event is null.
VERIFY(m_ongoing_navigate_event == nullptr);
// 24. Set navigation's ongoing navigate event to event.
m_ongoing_navigate_event = event;
// 25. Set navigation's focus changed during ongoing navigation to false.
m_focus_changed_during_ongoing_navigation = false;
// 26. Set navigation's suppress normal scroll restoration during ongoing navigation to false.
m_suppress_normal_scroll_restoration_during_ongoing_navigation = false;
// 27. Let dispatchResult be the result of dispatching event at navigation.
auto dispatch_result = dispatch_event(*event);
// 28. If dispatchResult is false:
if (!dispatch_result) {
// 1. If navigationType is "traverse", then consume history-action user activation given navigation's relevant global object.
if (navigation_type == NavigationType::Traverse)
window.consume_history_action_user_activation();
// 2. If event's abort controller's signal is not aborted, then abort the ongoing navigation given navigation.
if (!event->abort_controller()->signal()->aborted())
abort_the_ongoing_navigation();
// 3. Return false.
return false;
}
// 29. If event's interception state is not "none":
if (event->interception_state() != NavigateEvent::InterceptionState::None) {
// AD-HOC: A traverse navigate event fires from a session history traversal task with no JavaScript on the
// stack, and creating the transition's promises needs a running execution context.
TemporaryExecutionContext execution_context { realm };
// 1. Let fromNHE be the current entry of navigation.
auto from_nhe = current_entry();
// 2. Assert: fromNHE is not null.
VERIFY(from_nhe != nullptr);
// 3. Set navigation's transition to a new NavigationTransition created in navigation's relevant realm, with
// navigation type: navigationType
// from entry: fromNHE
// destination: event's destination
// committed promise: a new promise created in navigation's relevant realm
// finished promise: a new promise created in navigation's relevant realm
m_transition = NavigationTransition::create(navigation_type, *from_nhe, event->destination(), WebIDL::create_promise_for(window), WebIDL::create_promise_for(window));
// 4. Mark as handled navigation's transition's finished promise.
// NOTE: See the discussion about other finished promises to understand why this is done.
WebIDL::mark_promise_as_handled(*m_transition->finished());
// 5. Mark as handled navigation's transition's committed promise.
WebIDL::mark_promise_as_handled(*m_transition->committed());
}
// 30. If event's navigation precommit handler list is empty then commit event given apiMethodTracker.
if (event->navigation_precommit_handler_list().is_empty()) {
commit_a_navigate_event(event, api_method_tracker);
}
// 31. Otherwise:
else {
// NB: Like for the transition above, the precommit handlers can be invoked from a session history traversal
// task with no JavaScript on the stack.
TemporaryExecutionContext execution_context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };
// 1. Let precommitController be a new NavigationPrecommitController created in navigation's relevant realm,
// whose event is event.
auto precommit_controller = NavigationPrecommitController::create(event);
JS::Value precommit_controller_value = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, precommit_controller);
// 2. Let precommitPromisesList be an empty list.
GC::RootVector<GC::Ref<WebIDL::Promise>> precommit_promises_list;
// 3. For each handler of event's navigation precommit handler list:
for (auto const& handler : event->navigation_precommit_handler_list()) {
// 1. Append the result of invoking handler with « precommitController » to precommitPromisesList.
precommit_promises_list.append(WebIDL::invoke_promise_callback(handler, {}, ReadonlySpan<JS::Value> { &precommit_controller_value, 1 }));
}
// 4. Wait for all precommitPromisesList with the following success steps: commit event given apiMethodTracker,
// and the following failure step given reason: process navigate event handler failure given event and
// reason.
WebIDL::wait_for_all(
realm, precommit_promises_list,
GC::create_function(GC::Heap::the(), GC::captures(*this, event, api_method_tracker), [](auto& self, auto& event, auto& api_method_tracker, Vector<JS::Value> const&) {
self.commit_a_navigate_event(event, api_method_tracker);
}),
GC::create_function(GC::Heap::the(), GC::captures(*this, event), [](auto& self, auto& event, JS::Value reason) {
self.process_navigate_event_handler_failure(event, reason);
}));
}
// 32. If event's interception state is "none", then return true.
// 33. Return false.
return event->interception_state() == NavigateEvent::InterceptionState::None;
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#commit-a-navigate-event
void Navigation::commit_a_navigate_event(GC::Ref<NavigateEvent> event, GC::Ptr<NavigationAPIMethodTracker> api_method_tracker)
{
// 1. Let navigation be event's target.
// NB: Navigation is `this`.
// 2. Let navigable be event's relevant global object's navigable.
auto& window = event->relevant_window();
auto navigable = window.navigable();
// 3. If event's relevant global object's associated Document is not fully active, then return.
auto& document = window.associated_document();
if (!document.is_fully_active())
return;
// 4. If event's abort controller's signal is aborted, then return.
if (event->abort_controller()->signal()->aborted())
return;
// 5. Let endResultIsSameDocument be true if event's interception state is not "none" or event's destination's
// is same document is true.
bool const end_result_is_same_document = (event->interception_state() != NavigateEvent::InterceptionState::None) || event->destination()->same_document();
// 6. Prepare to run script given navigation's relevant settings object.
// NOTE: There's a massive spec note here
TemporaryExecutionContext execution_context { window.principal_realm(), TemporaryExecutionContext::CallbacksEnabled::Yes };
auto const navigation_type = event->navigation_type();
// 7. If event's interception state is not "none":
if (event->interception_state() != NavigateEvent::InterceptionState::None) {
// 1. Set event's interception state to "committed".
event->set_interception_state(NavigateEvent::InterceptionState::Committed);
// 2. Switch on event's navigationType:
// - "traverse":
if (navigation_type == Bindings::NavigationType::Traverse) {
// 1. Set navigation's suppress normal scroll restoration during ongoing navigation to true.
// NOTE: If event's scroll behavior was set to "after-transition", then scroll restoration will happen as part of finishing
// the relevant NavigateEvent. Otherwise, there will be no scroll restoration. That is, no navigation which is intercepted
// by intercept() goes through the normal scroll restoration process; scroll restoration for such navigations
// is either done manually, by the web developer, or is done after the transition.
m_suppress_normal_scroll_restoration_during_ongoing_navigation = true;
// 2. Let userInvolvement be "none".
auto user_involvement_for_resume = UserNavigationInvolvement::None;
// 3. If event's userInitiated is true, then set userInvolvement to "activation".
if (event->user_initiated())
user_involvement_for_resume = UserNavigationInvolvement::Activation;
// NOTE: At this point after interception, it is not consequential whether the
// activation was a result of browser UI.
// 4. Append the following session history traversal steps to navigable's traversable navigable:
// 1. Resume applying the traverse history step given event's destination's entry's session history
// entry's step, navigable's traversable navigable, and userInvolvement.
// NOTE: When resuming a traverse, we are already past the cancelation, initiator, and source snapshot
// checks, and this traversal has already been determined to be a same-document traversal.
// NB: The committed navigate event remains ongoing until the same-document entry update runs the
// navigate event intercept commit handler steps, so the operation must preserve it.
auto destination_entry = event->destination()->navigation_history_entry();
VERIFY(destination_entry);
auto target_step = destination_entry->session_history_entry().step().get<int>();
auto operation_id = navigable->page().history_executor().request_history_operation(ResumeTraverseHistoryOperationParameters {
.navigable_id = navigable->id(),
.target_step = target_step,
.user_involvement = user_involvement_for_resume,
});
event->set_resume_traversal_operation_id(operation_id);
}
// - "push"
// - "replace":
// Run the URL and history update steps given event's relevant global object's associated Document and event's
// destination's URL, with serializedData set to event's classic history API state and historyHandling set to
// event's navigationType.
if (navigation_type == NavigationType::Push || navigation_type == NavigationType::Replace) {
auto history_handling = navigation_type == NavigationType::Push ? HistoryHandlingBehavior::Push : HistoryHandlingBehavior::Replace;
perform_url_and_history_update_steps(document, event->destination()->raw_url(), event->classic_history_api_state(), history_handling);
}
// - "reload":
// Update the navigation API entries for a same-document navigation given navigation, navigable's active session
// history entry, and "reload".
if (navigation_type == NavigationType::Reload) {
update_the_navigation_api_entries_for_a_same_document_navigation(*navigable->active_session_history_entry(), NavigationType::Reload);
}
}
auto const event_was_intercepted = event->interception_state() != NavigateEvent::InterceptionState::None;
auto const same_document_entry_update_will_run_commit_handler_steps = end_result_is_same_document
&& (navigation_type == Bindings::NavigationType::Traverse
|| (!event_was_intercepted
&& (navigation_type == Bindings::NavigationType::Push
|| navigation_type == Bindings::NavigationType::Replace)));
if (end_result_is_same_document) {
// NB: Same-document Navigation API entry updates run these steps after currententrychange.
// If those steps have not started here, run them as a fallback for same-document paths that did not update
// entries. Intercepted push/replace navigations have already attempted their same-document entry update
// above, so keep this fallback enabled in case the navigate event handler detached its document and caused
// that update to return early due to entries and events being disabled.
if (!same_document_entry_update_will_run_commit_handler_steps
&& !event->has_started_navigate_event_intercept_commit_handler_steps())
run_the_navigate_event_intercept_commit_handler_steps(event, api_method_tracker);
}
// 8. If navigation's transition is not null, then resolve navigation's transition's committed promise with undefined.
if (m_transition)
WebIDL::resolve_promise(m_transition->committed());
// 9. If endResultIsSameDocument is false and apiMethodTracker is non-null, then clean up apiMethodTracker.
if (!end_result_is_same_document && api_method_tracker != nullptr)
clean_up(*api_method_tracker);
// 10. Clean up after running script given navigation's relevant settings object.
// NB: Handled by TemporaryExecutionContext destructor.
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#fire-a-traverse-navigate-event
bool Navigation::fire_a_traverse_navigate_event(NonnullRefPtr<SessionHistoryEntry> destination_she, UserNavigationInvolvement user_involvement)
{
// 1. Let event be the result of creating an event given NavigateEvent, in navigation's relevant realm.
// 2. Set event's classic history API state to null.
// AD-HOC: These are handled in the inner algorithm
// 3. Let destination be a new NavigationDestination created in navigation's relevant realm.
auto destination = NavigationDestination::create();
// 4. Set destination's URL to destinationSHE's URL.
destination->set_url(destination_she->url());
// 5. Let destinationNHE be the NavigationHistoryEntry in navigation's entry list whose session history entry is destinationSHE,
// or null if no such NavigationHistoryEntry exists.
auto destination_nhe = m_entry_list.find_if([destination_she](auto& nhe) {
return &nhe->session_history_entry() == destination_she;
});
// 6. If destinationNHE is non-null, then:
if (destination_nhe != m_entry_list.end()) {
// 1. Set destination's entry to destinationNHE.
destination->set_entry(*destination_nhe);
// 2. Set destination's state to destinationSHE's navigation API state.
destination->set_state(destination_she->navigation_api_state());
}
// 7. Otherwise:
else {
// 1. Set destination's entry to null.
destination->set_entry(nullptr);
// 2. Set destination's state to StructuredSerializeForStorage(null).
destination->set_state(MUST(structured_serialize_for_storage(window().principal_realm().vm(), JS::js_null())));
}
// 8. Set destination's is same document to true if destinationSHE's document is equal to
// navigation's relevant global object's associated Document; otherwise false.
auto& associated_document = window().associated_document();
destination->set_is_same_document(destination_she->document_state()->document_id() == associated_document.unique_id());
// 9. Return the result of performing the inner navigate event firing algorithm given navigation, "traverse",
// event, destination, userInvolvement, sourceElement, null, and null.
// AD-HOC: We don't pass the event, but we do pass the classic_history_api state at the end to be set later
return inner_navigate_event_firing_algorithm(NavigationType::Traverse, destination, user_involvement, {}, {}, {}, {});
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#fire-a-push/replace/reload-navigate-event
bool Navigation::fire_a_push_replace_reload_navigate_event(
NavigationType navigation_type,
URL::URL destination_url,
bool is_same_document,
UserNavigationInvolvement user_involvement,
GC::Ptr<DOM::Element> source_element,
Optional<GC::RootVector<XHR::FormDataEntry>&> form_data_entry_list,
Optional<StorageSerializationRecord> navigation_api_state,
Optional<StorageSerializationRecord> classic_history_api_state,
GC::Ptr<NavigationAPIMethodTracker> api_method_tracker)
{
// This fulfills the entry requirement: an optional serialized state navigationAPIState (default StructuredSerializeForStorage(null))
if (!navigation_api_state.has_value())
navigation_api_state = MUST(structured_serialize_for_storage(window().principal_realm().vm(), JS::js_null()));
// 1. Let document be navigation's relevant global object's associated Document.
auto& document = window().associated_document();
// 2. Inform the navigation API about aborting navigation in document's node navigable.
document.navigable()->inform_the_navigation_api_about_aborting_navigation();
// 3. If navigation has entries and events disabled, and apiMethodTracker is not null:
// NOTE: If navigation has entries and events disabled, then navigate() and reload() calls return promises that
// will never fulfill. We never create a NavigationHistoryEntry object for such Documents, there is no
// NavigationHistoryEntry to apply serializedState to, and there is no navigate event to include info with.
// So, we don't need to track this API method call after all. We need to check this after aborting previous
// navigations, in case the Document has became non-fully active as a result of a navigateerror event.
if (has_entries_and_events_disabled() && api_method_tracker) {
// 1. Set apiMethodTracker's pending to false.
api_method_tracker->pending = NavigationAPIMethodTracker::Pending::No;
// 2. Set apiMethodTracker to null.
api_method_tracker = nullptr;
}
// 4. If document is not fully active, then return false.
if (!document.is_fully_active())
return false;
// 5. Let event be the result of creating an event given NavigateEvent, in navigation's relevant realm.
// 6. Set event's classic history API state to classicHistoryAPIState.
// AD-HOC: These are handled in the inner algorithm
// 7. Let destination be a new NavigationDestination created in navigation's relevant realm.
auto destination = NavigationDestination::create();
// 8. Set destination's URL to destinationURL.
destination->set_url(destination_url);
// 9. Set destination's entry to null.
destination->set_entry(nullptr);
// 10. Set destination's state to navigationAPIState.
destination->set_state(*navigation_api_state);
// 11. Set destination's is same document to isSameDocument.
destination->set_is_same_document(is_same_document);
// 12. Return the result of performing the inner navigate event firing algorithm given navigation,
// navigationType, event, destination, userInvolvement, sourceElement, formDataEntryList, null, and
// apiMethodTracker.
// AD-HOC: We don't pass the event, but we do pass the classic_history_api state at the end to be set later
return inner_navigate_event_firing_algorithm(navigation_type, destination, user_involvement, source_element, move(form_data_entry_list), {}, move(classic_history_api_state), api_method_tracker);
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#fire-a-download-request-navigate-event
bool Navigation::fire_a_download_request_navigate_event(URL::URL destination_url, UserNavigationInvolvement user_involvement, GC::Ptr<DOM::Element> source_element, Utf16String filename)
{
// 1. Let event be the result of creating an event given NavigateEvent, in navigation's relevant realm.
// 2. Set event's classic history API state to classicHistoryAPIState.
// AD-HOC: These are handled in the inner algorithm
// 3. Let destination be a new NavigationDestination created in navigation's relevant realm.
auto destination = NavigationDestination::create();
// 4. Set destination's URL to destinationURL.
destination->set_url(destination_url);
// 5. Set destination's entry to null.
destination->set_entry(nullptr);
// 6. Set destination's state to StructuredSerializeForStorage(null).
destination->set_state(MUST(structured_serialize_for_storage(window().principal_realm().vm(), JS::js_null())));
// 7. Set destination's is same document to false.
destination->set_is_same_document(false);
// 8. Return the result of performing the inner navigate event firing algorithm given navigation,
// "push", event, destination, userInvolvement, sourceElement, null, and filename.
// AD-HOC: We don't pass the event, but we do pass the classic_history_api state at the end to be set later
return inner_navigate_event_firing_algorithm(NavigationType::Push, destination, user_involvement, source_element, {}, move(filename), {});
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#initialize-the-navigation-api-entries-for-a-new-document
void Navigation::initialize_the_navigation_api_entries_for_a_new_document(Vector<NonnullRefPtr<SessionHistoryEntry>> const& new_shes, NonnullRefPtr<SessionHistoryEntry> initial_she)
{
// 1. Assert: navigation's entry list is empty.
VERIFY(m_entry_list.is_empty());
// 2. Assert: navigation's current entry index is −1.
VERIFY(m_current_entry_index == -1);
// AD-HOC: This flag is only set when an about:blank page is modified by document.open(). Reset it now that a new
// navigation is happening.
m_was_initial_about_blank_opened = false;
// 3. If navigation has entries and events disabled, then return.
if (has_entries_and_events_disabled())
return;
// 4. For each newSHE of newSHEs:
for (auto const& new_she : new_shes) {
// 1. Let newNHE be a new NavigationHistoryEntry created in the relevant realm of navigation.
// 2. Set newNHE's session history entry to newSHE.
auto new_nhe = NavigationHistoryEntry::create(window(), new_she);
// 3. Append newNHE to navigation's entry list.
m_entry_list.append(new_nhe);
}
// 5. Set navigation's current entry index to the result of getting the navigation API entry index of initialSHE within navigation.
m_current_entry_index = get_the_navigation_api_entry_index(*initial_she);
}
void Navigation::initialize_the_navigation_api_entries_for_reconstructed_session_history(Vector<NonnullRefPtr<SessionHistoryEntry>> const& new_shes, NonnullRefPtr<SessionHistoryEntry> initial_she)
{
m_entry_list.clear();
m_current_entry_index = -1;
initialize_the_navigation_api_entries_for_a_new_document(new_shes, move(initial_she));
}
// https://html.spec.whatwg.org/multipage/nav-history-apis.html#update-the-navigation-api-entries-for-a-same-document-navigation
void Navigation::update_the_navigation_api_entries_for_a_same_document_navigation(NonnullRefPtr<SessionHistoryEntry> destination_she, NavigationType navigation_type)
{
auto& realm = window().principal_realm();
// 1. If navigation has entries and events disabled, then return.
if (has_entries_and_events_disabled())
return;
// 2. Let oldCurrentNHE be the current entry of navigation.
auto old_current_nhe = current_entry();
// 3. Let disposedNHEs be a new empty list.
GC::RootVector<GC::Ref<NavigationHistoryEntry>> disposed_nhes;
// 4. If navigationType is "traverse", then:
if (navigation_type == NavigationType::Traverse) {
// 1. Set navigation's current entry index to the result of getting the navigation API entry index of destinationSHE within navigation.
m_current_entry_index = get_the_navigation_api_entry_index(destination_she);
// 2. Assert: navigation's current entry index is not −1.
// NOTE: This algorithm is only called for same-document traversals.
// Cross-document traversals will instead call either initialize the navigation API entries for a new document
// or update the navigation API entries for reactivation
VERIFY(m_current_entry_index != -1);
}
// 5. Otherwise, if navigationType is "push", then:
else if (navigation_type == NavigationType::Push) {
// 1. Set navigation's current entry index to navigation's current entry index + 1.
m_current_entry_index++;
// 2. Let i be navigation's current entry index.
auto i = m_current_entry_index;
// 3. While i < navigation's entry list's size:
while (i < static_cast<i64>(m_entry_list.size())) {
// 1. Append navigation's entry list[i] to disposedNHEs.
disposed_nhes.append(m_entry_list[i]);
// 2. Set i to i + 1.
++i;
}
// 4. Remove all items in disposedNHEs from navigation's entry list.
m_entry_list.remove(m_current_entry_index, m_entry_list.size() - m_current_entry_index);
}
// 6. Otherwise, if navigationType is "replace", then:
else if (navigation_type == NavigationType::Replace) {
VERIFY(old_current_nhe != nullptr);
// 1. Append oldCurrentNHE to disposedNHEs.
disposed_nhes.append(*old_current_nhe);
}
// 7. If navigationType is "push" or "replace", then:
if (navigation_type == NavigationType::Push || navigation_type == NavigationType::Replace) {
// 1. Let newNHE be a new NavigationHistoryEntry created in the relevant realm of navigation.
// 2. Set newNHE's session history entry to destinationSHE.
auto new_nhe = NavigationHistoryEntry::create(window(), destination_she);
VERIFY(m_current_entry_index != -1);
// 3. Set navigation's entry list[navigation's current entry index] to newNHE.
if (m_current_entry_index < static_cast<i64>(m_entry_list.size()))
m_entry_list[m_current_entry_index] = new_nhe;
else {
VERIFY(m_current_entry_index == static_cast<i64>(m_entry_list.size()));
m_entry_list.append(new_nhe);
}
}
// NB: Resolving the committed promise in step 8 needs a running execution context, and cleaning that up would
// perform a microtask checkpoint when nothing else is running script, such as during a traversal. So this
// prepares to run script ahead of step 11, which keeps promise reactions from running before the
// currententrychange event handlers and the intercept() handlers.
TemporaryExecutionContext execution_context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };
// 8. If navigation's ongoing API method tracker is non-null, then notify about the committed-to entry
// given navigation's ongoing API method tracker and the current entry of navigation.
// NOTE: It is important to do this before firing the dispose or currententrychange events,
// since event handlers could start another navigation, or otherwise change the value of
// navigation's ongoing API method tracker.
if (m_ongoing_api_method_tracker != nullptr)
notify_about_the_committed_to_entry(*m_ongoing_api_method_tracker, *current_entry());
// 9. Let navigateEvent be navigation's ongoing navigate event.
auto navigate_event = m_ongoing_navigate_event;
// 10. Let apiMethodTracker be navigation's ongoing API method tracker.
auto api_method_tracker = m_ongoing_api_method_tracker;
// 11. Prepare to run script given navigation's relevant settings object.
// NB: Done before step 8.
// 12. Fire an event named currententrychange at navigation using NavigationCurrentEntryChangeEvent,
// with its navigationType attribute initialized to navigationType and its from initialized to oldCurrentNHE.
NavigationCurrentEntryChangeEventInit event_init { {}, *old_current_nhe, navigation_type };
dispatch_event(NavigationCurrentEntryChangeEvent::create(EventNames::currententrychange, event_init, HighResolutionTime::current_high_resolution_time(realm.global_object())));
// 13. For each disposedNHE of disposedNHEs:
for (auto& disposed_nhe : disposed_nhes) {
// 1. Fire an event named dispose at disposedNHE.
disposed_nhe->dispatch_event(DOM::Event::create(
EventNames::dispose,
{},
HighResolutionTime::current_high_resolution_time(relevant_global_object(window()))));
}
// 14. Run the navigate event intercept commit handler steps given navigation, navigateEvent, and apiMethodTracker.
if (navigate_event != nullptr
&& navigate_event == m_ongoing_navigate_event
&& !navigate_event->has_started_navigate_event_intercept_commit_handler_steps()) {
run_the_navigate_event_intercept_commit_handler_steps(*navigate_event, api_method_tracker);
}
// 15. Clean up after running script given navigation's relevant settings object.
// NB: Handled by TemporaryExecutionContext destructor from step 11.
}
}