Navigation.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  1. /*
  2. * Copyright (c) 2023, Andrew Kaster <akaster@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Heap/Heap.h>
  7. #include <LibJS/Runtime/Realm.h>
  8. #include <LibJS/Runtime/VM.h>
  9. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  10. #include <LibWeb/Bindings/Intrinsics.h>
  11. #include <LibWeb/Bindings/NavigationPrototype.h>
  12. #include <LibWeb/DOM/AbortController.h>
  13. #include <LibWeb/DOM/Document.h>
  14. #include <LibWeb/HTML/DocumentState.h>
  15. #include <LibWeb/HTML/ErrorEvent.h>
  16. #include <LibWeb/HTML/History.h>
  17. #include <LibWeb/HTML/NavigateEvent.h>
  18. #include <LibWeb/HTML/Navigation.h>
  19. #include <LibWeb/HTML/NavigationCurrentEntryChangeEvent.h>
  20. #include <LibWeb/HTML/NavigationDestination.h>
  21. #include <LibWeb/HTML/NavigationHistoryEntry.h>
  22. #include <LibWeb/HTML/NavigationTransition.h>
  23. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  24. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  25. #include <LibWeb/HTML/TraversableNavigable.h>
  26. #include <LibWeb/HTML/Window.h>
  27. #include <LibWeb/WebIDL/AbstractOperations.h>
  28. #include <LibWeb/XHR/FormData.h>
  29. namespace Web::HTML {
  30. JS_DEFINE_ALLOCATOR(Navigation);
  31. static NavigationResult navigation_api_method_tracker_derived_result(JS::NonnullGCPtr<NavigationAPIMethodTracker> api_method_tracker);
  32. NavigationAPIMethodTracker::NavigationAPIMethodTracker(JS::NonnullGCPtr<Navigation> navigation,
  33. Optional<String> key,
  34. JS::Value info,
  35. Optional<SerializationRecord> serialized_state,
  36. JS::GCPtr<NavigationHistoryEntry> commited_to_entry,
  37. JS::NonnullGCPtr<WebIDL::Promise> committed_promise,
  38. JS::NonnullGCPtr<WebIDL::Promise> finished_promise)
  39. : navigation(navigation)
  40. , key(move(key))
  41. , info(info)
  42. , serialized_state(move(serialized_state))
  43. , commited_to_entry(commited_to_entry)
  44. , committed_promise(committed_promise)
  45. , finished_promise(finished_promise)
  46. {
  47. }
  48. void NavigationAPIMethodTracker::visit_edges(Cell::Visitor& visitor)
  49. {
  50. Base::visit_edges(visitor);
  51. visitor.visit(navigation);
  52. visitor.visit(info);
  53. visitor.visit(commited_to_entry);
  54. visitor.visit(committed_promise);
  55. visitor.visit(finished_promise);
  56. }
  57. JS::NonnullGCPtr<Navigation> Navigation::create(JS::Realm& realm)
  58. {
  59. return realm.heap().allocate<Navigation>(realm, realm);
  60. }
  61. Navigation::Navigation(JS::Realm& realm)
  62. : DOM::EventTarget(realm)
  63. {
  64. }
  65. Navigation::~Navigation() = default;
  66. void Navigation::initialize(JS::Realm& realm)
  67. {
  68. Base::initialize(realm);
  69. WEB_SET_PROTOTYPE_FOR_INTERFACE(Navigation);
  70. }
  71. void Navigation::visit_edges(JS::Cell::Visitor& visitor)
  72. {
  73. Base::visit_edges(visitor);
  74. for (auto& entry : m_entry_list)
  75. visitor.visit(entry);
  76. visitor.visit(m_transition);
  77. visitor.visit(m_ongoing_navigate_event);
  78. visitor.visit(m_ongoing_api_method_tracker);
  79. visitor.visit(m_upcoming_non_traverse_api_method_tracker);
  80. for (auto& key_and_tracker : m_upcoming_traverse_api_method_trackers)
  81. visitor.visit(key_and_tracker.value);
  82. }
  83. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-entries
  84. Vector<JS::NonnullGCPtr<NavigationHistoryEntry>> Navigation::entries() const
  85. {
  86. // The entries() method steps are:
  87. // 1. If this has entries and events disabled, then return the empty list.
  88. if (has_entries_and_events_disabled())
  89. return {};
  90. // 2. Return this's entry list.
  91. // NOTE: Recall that because of Web IDL's sequence type conversion rules,
  92. // this will create a new JavaScript array object on each call.
  93. // That is, navigation.entries() !== navigation.entries().
  94. return m_entry_list;
  95. }
  96. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-current-entry
  97. JS::GCPtr<NavigationHistoryEntry> Navigation::current_entry() const
  98. {
  99. // The current entry of a Navigation navigation is the result of running the following steps:
  100. // 1. If navigation has entries and events disabled, then return null.
  101. if (has_entries_and_events_disabled())
  102. return nullptr;
  103. // 2. Assert: navigation's current entry index is not −1.
  104. VERIFY(m_current_entry_index != -1);
  105. // 3. Return navigation's entry list[navigation's current entry index].
  106. return m_entry_list[m_current_entry_index];
  107. }
  108. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-updatecurrententry
  109. WebIDL::ExceptionOr<void> Navigation::update_current_entry(NavigationUpdateCurrentEntryOptions options)
  110. {
  111. // The updateCurrentEntry(options) method steps are:
  112. // 1. Let current be the current entry of this.
  113. auto current = current_entry();
  114. // 2. If current is null, then throw an "InvalidStateError" DOMException.
  115. if (current == nullptr)
  116. return WebIDL::InvalidStateError::create(realm(), "Cannot update current NavigationHistoryEntry when there is no current entry"_fly_string);
  117. // 3. Let serializedState be StructuredSerializeForStorage(options["state"]), rethrowing any exceptions.
  118. auto serialized_state = TRY(structured_serialize_for_storage(vm(), options.state));
  119. // 4. Set current's session history entry's navigation API state to serializedState.
  120. current->session_history_entry().navigation_api_state = serialized_state;
  121. // 5. Fire an event named currententrychange at this using NavigationCurrentEntryChangeEvent,
  122. // with its navigationType attribute initialized to null and its from initialized to current.
  123. NavigationCurrentEntryChangeEventInit event_init = {};
  124. event_init.navigation_type = {};
  125. event_init.from = current;
  126. dispatch_event(HTML::NavigationCurrentEntryChangeEvent::construct_impl(realm(), HTML::EventNames::currententrychange, event_init));
  127. return {};
  128. }
  129. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-cangoback
  130. bool Navigation::can_go_back() const
  131. {
  132. // The canGoBack getter steps are:
  133. // 1. If this has entries and events disabled, then return false.
  134. if (has_entries_and_events_disabled())
  135. return false;
  136. // 2. Assert: navigation's current entry index is not −1.
  137. VERIFY(m_current_entry_index != -1);
  138. // 3. If this's current entry index is 0, then return false.
  139. // 4. Return true.
  140. return (m_current_entry_index != 0);
  141. }
  142. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-cangoforward
  143. bool Navigation::can_go_forward() const
  144. {
  145. // The canGoForward getter steps are:
  146. // 1. If this has entries and events disabled, then return false.
  147. if (has_entries_and_events_disabled())
  148. return false;
  149. // 2. Assert: navigation's current entry index is not −1.
  150. VERIFY(m_current_entry_index != -1);
  151. // 3. If this's current entry index is equal to this's entry list's size, then return false.
  152. // 4. Return true.
  153. return (m_current_entry_index != static_cast<i64>(m_entry_list.size()));
  154. }
  155. HistoryHandlingBehavior to_history_handling_behavior(Bindings::NavigationHistoryBehavior b)
  156. {
  157. // A history handling behavior is a NavigationHistoryBehavior that is either "push" or "replace",
  158. // i.e., that has been resolved away from any initial "auto" value.
  159. VERIFY(b != Bindings::NavigationHistoryBehavior::Auto);
  160. switch (b) {
  161. case Bindings::NavigationHistoryBehavior::Push:
  162. return HistoryHandlingBehavior::Push;
  163. case Bindings::NavigationHistoryBehavior::Replace:
  164. return HistoryHandlingBehavior::Replace;
  165. case Bindings::NavigationHistoryBehavior::Auto:
  166. VERIFY_NOT_REACHED();
  167. };
  168. VERIFY_NOT_REACHED();
  169. }
  170. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-navigate
  171. WebIDL::ExceptionOr<NavigationResult> Navigation::navigate(String url, NavigationNavigateOptions const& options)
  172. {
  173. auto& realm = this->realm();
  174. auto& vm = this->vm();
  175. // The navigate(options) method steps are:
  176. // 1. Parse url relative to this's relevant settings object.
  177. // If that returns failure, then return an early error result for a "SyntaxError" DOMException.
  178. // Otherwise, let urlRecord be the resulting URL record.
  179. auto url_record = relevant_settings_object(*this).parse_url(url);
  180. if (!url_record.is_valid())
  181. return early_error_result(WebIDL::SyntaxError::create(realm, "Cannot navigate to Invalid URL"_fly_string));
  182. // 2. Let document be this's relevant global object's associated Document.
  183. auto& document = verify_cast<HTML::Window>(relevant_global_object(*this)).associated_document();
  184. // 3. If options["history"] is "push", and the navigation must be a replace given urlRecord and document,
  185. // then return an early error result for a "NotSupportedError" DOMException.
  186. if (options.history == Bindings::NavigationHistoryBehavior::Push && navigation_must_be_a_replace(url_record, document))
  187. return early_error_result(WebIDL::NotSupportedError::create(realm, "Navigation must be a replace, but push was requested"_fly_string));
  188. // 4. Let state be options["state"], if it exists; otherwise, undefined.
  189. auto state = options.state.value_or(JS::js_undefined());
  190. // 5. Let serializedState be StructuredSerializeForStorage(state).
  191. // If this throws an exception, then return an early error result for that exception.
  192. // FIXME: Fix this spec grammaro in the note
  193. // NOTE: It is importantly to perform this step early, since serialization can invoke web developer code,
  194. // which in turn might change various things we check in later steps.
  195. auto serialized_state_or_error = structured_serialize_for_storage(vm, state);
  196. if (serialized_state_or_error.is_error()) {
  197. return early_error_result(serialized_state_or_error.release_error());
  198. }
  199. auto serialized_state = serialized_state_or_error.release_value();
  200. // 6. If document is not fully active, then return an early error result for an "InvalidStateError" DOMException.
  201. if (!document.is_fully_active())
  202. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document is not fully active"_fly_string));
  203. // 7. If document's unload counter is greater than 0, then return an early error result for an "InvalidStateError" DOMException.
  204. if (document.unload_counter() > 0)
  205. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document already unloaded"_fly_string));
  206. // 8. Let info be options["info"], if it exists; otherwise, undefined.
  207. auto info = options.info.value_or(JS::js_undefined());
  208. // 9. Let apiMethodTracker be the result of maybe setting the upcoming non-traverse API method tracker for this
  209. // given info and serializedState.
  210. auto api_method_tracker = maybe_set_the_upcoming_non_traverse_api_method_tracker(info, serialized_state);
  211. // 10. Navigate document's node navigable to urlRecord using document,
  212. // with historyHandling set to options["history"] and navigationAPIState set to serializedState.
  213. // FIXME: Fix spec typo here
  214. // NOTE: Unlike location.assign() and friends, which are exposed across origin-domain boundaries,
  215. // navigation.navigate() can only be accessed by code with direct synchronous access to the
  216. // window.navigation property. Thus, we avoid the complications about attributing the source document
  217. // of the navigation, and we don't need to deal with the allowed by sandboxing to navigate check and its
  218. // acccompanying exceptionsEnabled flag. We just treat all navigations as if they come from the Document
  219. // corresponding to this Navigation object itself (i.e., document).
  220. TRY(document.navigable()->navigate({ .url = url_record, .source_document = document, .history_handling = options.history, .navigation_api_state = move(serialized_state) }));
  221. // 11. If this's upcoming non-traverse API method tracker is apiMethodTracker, then:
  222. // NOTE: If the upcoming non-traverse API method tracker is still apiMethodTracker, this means that the navigate
  223. // algorithm bailed out before ever getting to the inner navigate event firing algorithm which would promote
  224. // that upcoming API method tracker to ongoing.
  225. if (m_upcoming_non_traverse_api_method_tracker == api_method_tracker) {
  226. m_upcoming_non_traverse_api_method_tracker = nullptr;
  227. return early_error_result(WebIDL::AbortError::create(realm, "Navigation aborted"_fly_string));
  228. }
  229. // 12. Return a navigation API method tracker-derived result for apiMethodTracker.
  230. return navigation_api_method_tracker_derived_result(api_method_tracker);
  231. }
  232. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-reload
  233. WebIDL::ExceptionOr<NavigationResult> Navigation::reload(NavigationReloadOptions const& options)
  234. {
  235. auto& realm = this->realm();
  236. auto& vm = this->vm();
  237. // The reload(options) method steps are:
  238. // 1. Let document be this's relevant global object's associated Document.
  239. auto& document = verify_cast<HTML::Window>(relevant_global_object(*this)).associated_document();
  240. // 2. Let serializedState be StructuredSerializeForStorage(undefined).
  241. auto serialized_state = MUST(structured_serialize_for_storage(vm, JS::js_undefined()));
  242. // 3. If options["state"] exists, then set serializedState to StructuredSerializeForStorage(options["state"]).
  243. // If this throws an exception, then return an early error result for that exception.
  244. // NOTE: It is importantly to perform this step early, since serialization can invoke web developer
  245. // code, which in turn might change various things we check in later steps.
  246. if (options.state.has_value()) {
  247. auto serialized_state_or_error = structured_serialize_for_storage(vm, options.state.value());
  248. if (serialized_state_or_error.is_error())
  249. return early_error_result(serialized_state_or_error.release_error());
  250. serialized_state = serialized_state_or_error.release_value();
  251. }
  252. // 4. Otherwise:
  253. else {
  254. // 1. Let current be the current entry of this.
  255. auto current = current_entry();
  256. // 2. If current is not null, then set serializedState to current's session history entry's navigation API state.
  257. if (current != nullptr)
  258. serialized_state = current->session_history_entry().navigation_api_state;
  259. }
  260. // 5. If document is not fully active, then return an early error result for an "InvalidStateError" DOMException.
  261. if (!document.is_fully_active())
  262. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document is not fully active"_fly_string));
  263. // 6. If document's unload counter is greater than 0, then return an early error result for an "InvalidStateError" DOMException.
  264. if (document.unload_counter() > 0)
  265. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document already unloaded"_fly_string));
  266. // 7. Let info be options["info"], if it exists; otherwise, undefined.
  267. auto info = options.info.value_or(JS::js_undefined());
  268. // 8. Let apiMethodTracker be the result of maybe setting the upcoming non-traverse API method tracker for this given info and serializedState.
  269. auto api_method_tracker = maybe_set_the_upcoming_non_traverse_api_method_tracker(info, serialized_state);
  270. // 9. Reload document's node navigable with navigationAPIState set to serializedState.
  271. // FIXME: Pass serialized_state to reload
  272. document.navigable()->reload();
  273. return navigation_api_method_tracker_derived_result(api_method_tracker);
  274. }
  275. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-traverseto
  276. WebIDL::ExceptionOr<NavigationResult> Navigation::traverse_to(String key, NavigationOptions const& options)
  277. {
  278. auto& realm = this->realm();
  279. // The traverseTo(key, options) method steps are:
  280. // 1. If this's current entry index is −1, then return an early error result for an "InvalidStateError" DOMException.
  281. if (m_current_entry_index == -1)
  282. return early_error_result(WebIDL::InvalidStateError::create(realm, "Cannot traverseTo: no current session history entry"_fly_string));
  283. // 2. If this's entry list does not contain a NavigationHistoryEntry whose session history entry's navigation API key equals key,
  284. // then return an early error result for an "InvalidStateError" DOMException.
  285. auto it = m_entry_list.find_if([&key](auto const& entry) {
  286. return entry->session_history_entry().navigation_api_key == key;
  287. });
  288. if (it == m_entry_list.end())
  289. return early_error_result(WebIDL::InvalidStateError::create(realm, "Cannot traverseTo: key not found in session history list"_fly_string));
  290. // 3. Return the result of performing a navigation API traversal given this, key, and options.
  291. return perform_a_navigation_api_traversal(key, options);
  292. }
  293. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#performing-a-navigation-api-traversal
  294. WebIDL::ExceptionOr<NavigationResult> Navigation::back(NavigationOptions const& options)
  295. {
  296. auto& realm = this->realm();
  297. // The back(options) method steps are:
  298. // 1. If this's current entry index is −1 or 0, then return an early error result for an "InvalidStateError" DOMException.
  299. if (m_current_entry_index == -1 || m_current_entry_index == 0)
  300. return early_error_result(WebIDL::InvalidStateError::create(realm, "Cannot navigate back: no previous session history entry"_fly_string));
  301. // 2. Let key be this's entry list[this's current entry index − 1]'s session history entry's navigation API key.
  302. auto key = m_entry_list[m_current_entry_index - 1]->session_history_entry().navigation_api_key;
  303. // 3. Return the result of performing a navigation API traversal given this, key, and options.
  304. return perform_a_navigation_api_traversal(key, options);
  305. }
  306. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-forward
  307. WebIDL::ExceptionOr<NavigationResult> Navigation::forward(NavigationOptions const& options)
  308. {
  309. auto& realm = this->realm();
  310. // The forward(options) method steps are:
  311. // 1. If this's current entry index is −1 or is equal to this's entry list's size − 1,
  312. // then return an early error result for an "InvalidStateError" DOMException.
  313. if (m_current_entry_index == -1 || m_current_entry_index == static_cast<i64>(m_entry_list.size() - 1))
  314. return early_error_result(WebIDL::InvalidStateError::create(realm, "Cannot navigate forward: no next session history entry"_fly_string));
  315. // 2. Let key be this's entry list[this's current entry index + 1]'s session history entry's navigation API key.
  316. auto key = m_entry_list[m_current_entry_index + 1]->session_history_entry().navigation_api_key;
  317. // 3. Return the result of performing a navigation API traversal given this, key, and options.
  318. return perform_a_navigation_api_traversal(key, options);
  319. }
  320. void Navigation::set_onnavigate(WebIDL::CallbackType* event_handler)
  321. {
  322. set_event_handler_attribute(HTML::EventNames::navigate, event_handler);
  323. }
  324. WebIDL::CallbackType* Navigation::onnavigate()
  325. {
  326. return event_handler_attribute(HTML::EventNames::navigate);
  327. }
  328. void Navigation::set_onnavigatesuccess(WebIDL::CallbackType* event_handler)
  329. {
  330. set_event_handler_attribute(HTML::EventNames::navigatesuccess, event_handler);
  331. }
  332. WebIDL::CallbackType* Navigation::onnavigatesuccess()
  333. {
  334. return event_handler_attribute(HTML::EventNames::navigatesuccess);
  335. }
  336. void Navigation::set_onnavigateerror(WebIDL::CallbackType* event_handler)
  337. {
  338. set_event_handler_attribute(HTML::EventNames::navigateerror, event_handler);
  339. }
  340. WebIDL::CallbackType* Navigation::onnavigateerror()
  341. {
  342. return event_handler_attribute(HTML::EventNames::navigateerror);
  343. }
  344. void Navigation::set_oncurrententrychange(WebIDL::CallbackType* event_handler)
  345. {
  346. set_event_handler_attribute(HTML::EventNames::currententrychange, event_handler);
  347. }
  348. WebIDL::CallbackType* Navigation::oncurrententrychange()
  349. {
  350. return event_handler_attribute(HTML::EventNames::currententrychange);
  351. }
  352. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#has-entries-and-events-disabled
  353. bool Navigation::has_entries_and_events_disabled() const
  354. {
  355. // A Navigation navigation has entries and events disabled if the following steps return true:
  356. // 1. Let document be navigation's relevant global object's associated Document.
  357. auto const& document = verify_cast<HTML::Window>(relevant_global_object(*this)).associated_document();
  358. // 2. If document is not fully active, then return true.
  359. if (!document.is_fully_active())
  360. return true;
  361. // 3. If document's is initial about:blank is true, then return true.
  362. if (document.is_initial_about_blank())
  363. return true;
  364. // 4. If document's origin is opaque, then return true.
  365. if (document.origin().is_opaque())
  366. return true;
  367. // 5. Return false.
  368. return false;
  369. }
  370. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#getting-the-navigation-api-entry-index
  371. i64 Navigation::get_the_navigation_api_entry_index(SessionHistoryEntry const& she) const
  372. {
  373. // To get the navigation API entry index of a session history entry she within a Navigation navigation:
  374. // 1. Let index be 0.
  375. i64 index = 0;
  376. // 2. For each nhe of navigation's entry list:
  377. for (auto const& nhe : m_entry_list) {
  378. // 1. If nhe's session history entry is equal to she, then return index.
  379. if (&nhe->session_history_entry() == &she)
  380. return index;
  381. // 2. Increment index by 1.
  382. ++index;
  383. }
  384. // 3. Return −1.
  385. return -1;
  386. }
  387. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-api-early-error-result
  388. NavigationResult Navigation::early_error_result(AnyException e)
  389. {
  390. auto& vm = this->vm();
  391. // An early error result for an exception e is a NavigationResult dictionary instance given by
  392. // «[ "committed" → a promise rejected with e, "finished" → a promise rejected with e ]».
  393. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, e);
  394. return {
  395. .committed = WebIDL::create_rejected_promise(realm(), *throw_completion.value())->promise(),
  396. .finished = WebIDL::create_rejected_promise(realm(), *throw_completion.value())->promise(),
  397. };
  398. }
  399. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-api-method-tracker-derived-result
  400. NavigationResult navigation_api_method_tracker_derived_result(JS::NonnullGCPtr<NavigationAPIMethodTracker> api_method_tracker)
  401. {
  402. // A navigation API method tracker-derived result for a navigation API method tracker is a NavigationResult
  403. /// dictionary instance given by «[ "committed" apiMethodTracker's committed promise, "finished" → apiMethodTracker's finished promise ]».
  404. return {
  405. api_method_tracker->committed_promise->promise(),
  406. api_method_tracker->finished_promise->promise(),
  407. };
  408. }
  409. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#upcoming-non-traverse-api-method-tracker
  410. JS::NonnullGCPtr<NavigationAPIMethodTracker> Navigation::maybe_set_the_upcoming_non_traverse_api_method_tracker(JS::Value info, Optional<SerializationRecord> serialized_state)
  411. {
  412. auto& realm = relevant_realm(*this);
  413. auto& vm = this->vm();
  414. // To maybe set the upcoming non-traverse API method tracker given a Navigation navigation,
  415. // a JavaScript value info, and a serialized state-or-null serializedState:
  416. // 1. Let committedPromise and finishedPromise be new promises created in navigation's relevant realm.
  417. auto committed_promise = WebIDL::create_promise(realm);
  418. auto finished_promise = WebIDL::create_promise(realm);
  419. // 2. Mark as handled finishedPromise.
  420. // NOTE: The web developer doesn’t necessarily care about finishedPromise being rejected:
  421. // - They might only care about committedPromise.
  422. // - They could be doing multiple synchronous navigations within the same task,
  423. // in which case all but the last will be aborted (causing their finishedPromise to reject).
  424. // This could be an application bug, but also could just be an emergent feature of disparate
  425. // parts of the application overriding each others' actions.
  426. // - They might prefer to listen to other transition-failure signals instead of finishedPromise, e.g.,
  427. // the navigateerror event, or the navigation.transition.finished promise.
  428. // As such, we mark it as handled to ensure that it never triggers unhandledrejection events.
  429. WebIDL::mark_promise_as_handled(finished_promise);
  430. // 3. Let apiMethodTracker be a new navigation API method tracker with:
  431. // navigation object: navigation
  432. // key: null
  433. // info: info
  434. // serialized state: serializedState
  435. // comitted-to entry: null
  436. // comitted promise: committedPromise
  437. // finished promise: finishedPromise
  438. auto api_method_tracker = vm.heap().allocate_without_realm<NavigationAPIMethodTracker>(
  439. /* .navigation = */ *this,
  440. /* .key = */ OptionalNone {},
  441. /* .info = */ info,
  442. /* .serialized_state = */ move(serialized_state),
  443. /* .commited_to_entry = */ nullptr,
  444. /* .committed_promise = */ committed_promise,
  445. /* .finished_promise = */ finished_promise);
  446. // 4. Assert: navigation's upcoming non-traverse API method tracker is null.
  447. VERIFY(m_upcoming_non_traverse_api_method_tracker == nullptr);
  448. // 5. If navigation does not have entries and events disabled,
  449. // then set navigation's upcoming non-traverse API method tracker to apiMethodTracker.
  450. // NOTE: If navigation has entries and events disabled, then committedPromise and finishedPromise will never fulfill
  451. // (since we never create a NavigationHistoryEntry object for such Documents, and so we have nothing to resolve them with);
  452. // there is no NavigationHistoryEntry to apply serializedState to; and there is no navigate event to include info with.
  453. // So, we don't need to track this API method call after all.
  454. if (!has_entries_and_events_disabled())
  455. m_upcoming_non_traverse_api_method_tracker = api_method_tracker;
  456. // 6. Return apiMethodTracker.
  457. return api_method_tracker;
  458. }
  459. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#add-an-upcoming-traverse-api-method-tracker
  460. JS::NonnullGCPtr<NavigationAPIMethodTracker> Navigation::add_an_upcoming_traverse_api_method_tracker(String destination_key, JS::Value info)
  461. {
  462. auto& vm = this->vm();
  463. auto& realm = relevant_realm(*this);
  464. // To add an upcoming traverse API method tracker given a Navigation navigation, a string destinationKey, and a JavaScript value info:
  465. // 1. Let committedPromise and finishedPromise be new promises created in navigation's relevant realm.
  466. auto committed_promise = WebIDL::create_promise(realm);
  467. auto finished_promise = WebIDL::create_promise(realm);
  468. // 2. Mark as handled finishedPromise.
  469. // NOTE: See the previous discussion about why this is done
  470. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#note-mark-as-handled-navigation-api-finished
  471. WebIDL::mark_promise_as_handled(*finished_promise);
  472. // 3. Let apiMethodTracker be a new navigation API method tracker with:
  473. // navigation object: navigation
  474. // key: destinationKey
  475. // info: info
  476. // serialized state: null
  477. // comitted-to entry: null
  478. // comitted promise: committedPromise
  479. // finished promise: finishedPromise
  480. auto api_method_tracker = vm.heap().allocate_without_realm<NavigationAPIMethodTracker>(
  481. /* .navigation = */ *this,
  482. /* .key = */ destination_key,
  483. /* .info = */ info,
  484. /* .serialized_state = */ OptionalNone {},
  485. /* .commited_to_entry = */ nullptr,
  486. /* .committed_promise = */ committed_promise,
  487. /* .finished_promise = */ finished_promise);
  488. // 4. Set navigation's upcoming traverse API method trackers[key] to apiMethodTracker.
  489. // FIXME: Fix spec typo key --> destinationKey
  490. m_upcoming_traverse_api_method_trackers.set(destination_key, api_method_tracker);
  491. // 5. Return apiMethodTracker.
  492. return api_method_tracker;
  493. }
  494. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#performing-a-navigation-api-traversal
  495. WebIDL::ExceptionOr<NavigationResult> Navigation::perform_a_navigation_api_traversal(String key, NavigationOptions const& options)
  496. {
  497. auto& realm = this->realm();
  498. // To perform a navigation API traversal given a Navigation navigation, a string key, and a NavigationOptions options:
  499. // 1. Let document be this's relevant global object's associated Document.
  500. auto& document = verify_cast<HTML::Window>(relevant_global_object(*this)).associated_document();
  501. // 2. If document is not fully active, then return an early error result for an "InvalidStateError" DOMException.
  502. if (!document.is_fully_active())
  503. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document is not fully active"_fly_string));
  504. // 3. If document's unload counter is greater than 0, then return an early error result for an "InvalidStateError" DOMException.
  505. if (document.unload_counter() > 0)
  506. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document already unloaded"_fly_string));
  507. // 4. Let current be the current entry of navigation.
  508. auto current = current_entry();
  509. // 5. If key equals current's session history entry's navigation API key, then return
  510. // «[ "committed" → a promise resolved with current, "finished" → a promise resolved with current ]».
  511. if (key == current->session_history_entry().navigation_api_key) {
  512. return NavigationResult {
  513. .committed = WebIDL::create_resolved_promise(realm, current)->promise(),
  514. .finished = WebIDL::create_resolved_promise(realm, current)->promise()
  515. };
  516. }
  517. // 6. If navigation's upcoming traverse API method trackers[key] exists,
  518. // then return a navigation API method tracker-derived result for navigation's upcoming traverse API method trackers[key].
  519. if (auto maybe_tracker = m_upcoming_traverse_api_method_trackers.get(key); maybe_tracker.has_value())
  520. return navigation_api_method_tracker_derived_result(maybe_tracker.value());
  521. // 7. Let info be options["info"], if it exists; otherwise, undefined.
  522. auto info = options.info.value_or(JS::js_undefined());
  523. // 8. Let apiMethodTracker be the result of adding an upcoming traverse API method tracker for navigation given key and info.
  524. auto api_method_tracker = add_an_upcoming_traverse_api_method_tracker(key, info);
  525. // 9. Let navigable be document's node navigable.
  526. auto navigable = document.navigable();
  527. // 10. Let traversable be navigable's traversable navigable.
  528. auto traversable = navigable->traversable_navigable();
  529. // 11. Let sourceSnapshotParams be the result of snapshotting source snapshot params given document.
  530. auto source_snapshot_params = document.snapshot_source_snapshot_params();
  531. // 12. Append the following session history traversal steps to traversable:
  532. traversable->append_session_history_traversal_steps([key, api_method_tracker, navigable, source_snapshot_params, traversable, this] {
  533. // 1. Let navigableSHEs be the result of getting session history entries given navigable.
  534. auto navigable_shes = navigable->get_session_history_entries();
  535. // 2. Let targetSHE be the session history entry in navigableSHEs whose navigation API key is key. If no such entry exists, then:
  536. auto it = navigable_shes.find_if([&key](auto const& entry) {
  537. return entry->navigation_api_key == key;
  538. });
  539. if (it == navigable_shes.end()) {
  540. // NOTE: This path is taken if navigation's entry list was outdated compared to navigableSHEs,
  541. // which can occur for brief periods while all the relevant threads and processes are being synchronized in reaction to a history change.
  542. // 1. Queue a global task on the navigation and traversal task source given navigation's relevant global object
  543. // to reject the finished promise for apiMethodTracker with an "InvalidStateError" DOMException.
  544. queue_global_task(HTML::Task::Source::NavigationAndTraversal, relevant_global_object(*this), [this, api_method_tracker] {
  545. auto& reject_realm = relevant_realm(*this);
  546. TemporaryExecutionContext execution_context { relevant_settings_object(*this) };
  547. WebIDL::reject_promise(reject_realm, api_method_tracker->finished_promise,
  548. WebIDL::InvalidStateError::create(reject_realm, "Cannot traverse with stale session history entry"_fly_string));
  549. });
  550. // 2. Abort these steps.
  551. return;
  552. }
  553. auto target_she = *it;
  554. // 3. If targetSHE is navigable's active session history entry, then abort these steps.
  555. // NOTE: This can occur if a previously queued traversal already took us to this session history entry.
  556. // In that case the previous traversal will have dealt with apiMethodTracker already.
  557. if (target_she == navigable->active_session_history_entry())
  558. return;
  559. // 4. Let result be the result of applying the traverse history step given by targetSHE's step to traversable,
  560. // given sourceSnapshotParams, navigable, and "none".
  561. auto result = traversable->apply_the_traverse_history_step(target_she->step.get<int>(), source_snapshot_params, navigable, UserNavigationInvolvement::None);
  562. // NOTE: When result is "canceled-by-beforeunload" or "initiator-disallowed", the navigate event was never fired,
  563. // aborting the ongoing navigation would not be correct; it would result in a navigateerror event without a
  564. // preceding navigate event. In the "canceled-by-navigate" case, navigate is fired, but the inner navigate event
  565. // firing algorithm will take care of aborting the ongoing navigation.
  566. // 5. If result is "canceled-by-beforeunload", then queue a global task on the navigation and traversal task source
  567. // given navigation's relevant global object to reject the finished promise for apiMethodTracker with a
  568. // new "AbortError" DOMException created in navigation's relevant realm.
  569. auto& realm = relevant_realm(*this);
  570. auto& global = relevant_global_object(*this);
  571. if (result == TraversableNavigable::HistoryStepResult::CanceledByBeforeUnload) {
  572. queue_global_task(Task::Source::NavigationAndTraversal, global, [this, api_method_tracker, &realm] {
  573. TemporaryExecutionContext execution_context { relevant_settings_object(*this) };
  574. reject_the_finished_promise(api_method_tracker, WebIDL::AbortError::create(realm, "Navigation cancelled by beforeunload"_fly_string));
  575. });
  576. }
  577. // 6. If result is "initiator-disallowed", then queue a global task on the navigation and traversal task source
  578. // given navigation's relevant global object to reject the finished promise for apiMethodTracker with a
  579. // new "SecurityError" DOMException created in navigation's relevant realm.
  580. if (result == TraversableNavigable::HistoryStepResult::InitiatorDisallowed) {
  581. queue_global_task(Task::Source::NavigationAndTraversal, global, [this, api_method_tracker, &realm] {
  582. TemporaryExecutionContext execution_context { relevant_settings_object(*this) };
  583. reject_the_finished_promise(api_method_tracker, WebIDL::SecurityError::create(realm, "Navigation disallowed from this origin"_fly_string));
  584. });
  585. }
  586. });
  587. // 13. Return a navigation API method tracker-derived result for apiMethodTracker.
  588. return navigation_api_method_tracker_derived_result(api_method_tracker);
  589. }
  590. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#abort-the-ongoing-navigation
  591. void Navigation::abort_the_ongoing_navigation(Optional<JS::NonnullGCPtr<WebIDL::DOMException>> error)
  592. {
  593. auto& realm = relevant_realm(*this);
  594. // To abort the ongoing navigation given a Navigation navigation and an optional DOMException error:
  595. // 1. Let event be navigation's ongoing navigate event.
  596. auto event = ongoing_navigate_event();
  597. // 2. Assert: event is not null.
  598. VERIFY(event != nullptr);
  599. // 3. Set navigation's focus changed during ongoing navigation to false.
  600. m_focus_changed_during_ongoing_navigation = false;
  601. // 4. Set navigation's suppress normal scroll restoration during ongoing navigation to false.
  602. m_suppress_scroll_restoration_during_ongoing_navigation = false;
  603. // 5. If error was not given, then let error be a new "AbortError" DOMException created in navigation's relevant realm.
  604. if (!error.has_value())
  605. error = WebIDL::AbortError::create(realm, "Navigation aborted"_fly_string);
  606. VERIFY(error.has_value());
  607. // 6. If event's dispatch flag is set, then set event's canceled flag to true.
  608. if (event->dispatched())
  609. event->set_cancelled(true);
  610. // 7. Signal abort on event's abort controller given error.
  611. event->abort_controller()->abort(error.value());
  612. // 8. Set navigation's ongoing navigate event to null.
  613. m_ongoing_navigate_event = nullptr;
  614. // 9. Fire an event named navigateerror at navigation using ErrorEvent, with error initialized to error,
  615. // and message, filename, lineno, and colno initialized to appropriate values that can be extracted
  616. // from error and the current JavaScript stack in the same underspecified way that the report the exception algorithm does.
  617. ErrorEventInit event_init = {};
  618. event_init.error = error.value();
  619. // FIXME: Extract information from the exception and the JS context in the wishy-washy way the spec says here.
  620. event_init.filename = String {};
  621. event_init.colno = 0;
  622. event_init.lineno = 0;
  623. event_init.message = String {};
  624. dispatch_event(ErrorEvent::create(realm, EventNames::navigateerror, event_init));
  625. // 10. If navigation's ongoing API method tracker is non-null, then reject the finished promise for apiMethodTracker with error.
  626. if (m_ongoing_api_method_tracker != nullptr)
  627. WebIDL::reject_promise(realm, m_ongoing_api_method_tracker->finished_promise, error.value());
  628. // 11. If navigation's transition is not null, then:
  629. if (m_transition != nullptr) {
  630. // 1. Reject navigation's transition's finished promise with error.
  631. m_transition->finished()->reject(error.value());
  632. // 2. Set navigation's transition to null.
  633. m_transition = nullptr;
  634. }
  635. }
  636. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#promote-an-upcoming-api-method-tracker-to-ongoing
  637. void Navigation::promote_an_upcoming_api_method_tracker_to_ongoing(Optional<String> destination_key)
  638. {
  639. // 1. Assert: navigation's ongoing API method tracker is null.
  640. VERIFY(m_ongoing_api_method_tracker == nullptr);
  641. // 2. If destinationKey is not null, then:
  642. if (destination_key.has_value()) {
  643. // 1. Assert: navigation's upcoming non-traverse API method tracker is null.
  644. VERIFY(m_upcoming_non_traverse_api_method_tracker == nullptr);
  645. // 2. If navigation's upcoming traverse API method trackers[destinationKey] exists, then:
  646. if (auto tracker = m_upcoming_traverse_api_method_trackers.get(destination_key.value()); tracker.has_value()) {
  647. // 1. Set navigation's ongoing API method tracker to navigation's upcoming traverse API method trackers[destinationKey].
  648. m_ongoing_api_method_tracker = tracker.value();
  649. // 2. Remove navigation's upcoming traverse API method trackers[destinationKey].
  650. m_upcoming_traverse_api_method_trackers.remove(destination_key.value());
  651. }
  652. }
  653. // 3. Otherwise:
  654. else {
  655. // 1. Set navigation's ongoing API method tracker to navigation's upcoming non-traverse API method tracker.
  656. m_ongoing_api_method_tracker = m_upcoming_non_traverse_api_method_tracker;
  657. // 2. Set navigation's upcoming non-traverse API method tracker to null.
  658. m_upcoming_non_traverse_api_method_tracker = nullptr;
  659. }
  660. }
  661. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-api-method-tracker-clean-up
  662. void Navigation::clean_up(JS::NonnullGCPtr<NavigationAPIMethodTracker> api_method_tracker)
  663. {
  664. // 1. Let navigation be apiMethodTracker's navigation object.
  665. VERIFY(api_method_tracker->navigation == this);
  666. // 2. If navigation's ongoing API method tracker is apiMethodTracker, then set navigation's ongoing API method tracker to null.
  667. if (m_ongoing_api_method_tracker == api_method_tracker) {
  668. m_ongoing_api_method_tracker = nullptr;
  669. }
  670. // 3. Otherwise:
  671. else {
  672. // 1. Let key be apiMethodTracker's key.
  673. auto& key = api_method_tracker->key;
  674. // 2. Assert: key is not null.
  675. VERIFY(key.has_value());
  676. // 3. Assert: navigation's upcoming traverse API method trackers[key] exists.
  677. VERIFY(m_upcoming_traverse_api_method_trackers.contains(*key));
  678. // 4. Remove navigation's upcoming traverse API method trackers[key].
  679. m_upcoming_traverse_api_method_trackers.remove(*key);
  680. }
  681. }
  682. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#resolve-the-finished-promise
  683. void Navigation::resolve_the_finished_promise(JS::NonnullGCPtr<NavigationAPIMethodTracker> api_method_tracker)
  684. {
  685. auto& realm = this->realm();
  686. // 1. Resolve apiMethodTracker's committed promise with its committed-to entry.
  687. // NOTE: Usually, notify about the committed-to entry has previously been called on apiMethodTracker,
  688. // and so this will do nothing. However, in some cases resolve the finished promise is called
  689. // directly, in which case this step is necessary.
  690. WebIDL::resolve_promise(realm, api_method_tracker->committed_promise, api_method_tracker->commited_to_entry);
  691. // 2. Resolve apiMethodTracker's finished promise with its committed-to entry.
  692. WebIDL::resolve_promise(realm, api_method_tracker->finished_promise, api_method_tracker->commited_to_entry);
  693. // 3. Clean up apiMethodTracker.
  694. clean_up(api_method_tracker);
  695. }
  696. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#reject-the-finished-promise
  697. void Navigation::reject_the_finished_promise(JS::NonnullGCPtr<NavigationAPIMethodTracker> api_method_tracker, JS::Value exception)
  698. {
  699. auto& realm = this->realm();
  700. // 1. Reject apiMethodTracker's committed promise with exception.
  701. // NOTE: This will do nothing if apiMethodTracker's committed promise was previously resolved
  702. // via notify about the committed-to entry.
  703. WebIDL::reject_promise(realm, api_method_tracker->committed_promise, exception);
  704. // 2. Reject apiMethodTracker's finished promise with exception.
  705. WebIDL::reject_promise(realm, api_method_tracker->finished_promise, exception);
  706. // 3. Clean up apiMethodTracker.
  707. clean_up(api_method_tracker);
  708. }
  709. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#notify-about-the-committed-to-entry
  710. void Navigation::notify_about_the_committed_to_entry(JS::NonnullGCPtr<NavigationAPIMethodTracker> api_method_tracker, JS::NonnullGCPtr<NavigationHistoryEntry> nhe)
  711. {
  712. auto& realm = this->realm();
  713. // 1. Set apiMethodTracker's committed-to entry to nhe.
  714. api_method_tracker->commited_to_entry = nhe;
  715. // 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.'
  716. // NOTE: If it's null, then we're traversing to nhe via navigation.traverseTo(), which does not allow changing the state.
  717. if (api_method_tracker->serialized_state.has_value()) {
  718. // NOTE: At this point, apiMethodTracker's serialized state is no longer needed.
  719. // Implementations might want to clear it out to avoid keeping it alive for the lifetime of the navigation API method tracker.
  720. nhe->session_history_entry().navigation_api_state = *api_method_tracker->serialized_state;
  721. api_method_tracker->serialized_state = {};
  722. }
  723. // 3. Resolve apiMethodTracker's committed promise with nhe.
  724. TemporaryExecutionContext execution_context { relevant_settings_object(*this) };
  725. WebIDL::resolve_promise(realm, api_method_tracker->committed_promise, nhe);
  726. }
  727. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#inner-navigate-event-firing-algorithm
  728. bool Navigation::inner_navigate_event_firing_algorithm(
  729. Bindings::NavigationType navigation_type,
  730. JS::NonnullGCPtr<NavigationDestination> destination,
  731. UserNavigationInvolvement user_involvement,
  732. Optional<Vector<XHR::FormDataEntry>&> form_data_entry_list,
  733. Optional<String> download_request_filename,
  734. Optional<SerializationRecord> classic_history_api_state)
  735. {
  736. auto& realm = relevant_realm(*this);
  737. // 1. If navigation has entries and events disabled, then:
  738. // NOTE: These assertions holds because traverseTo(), back(), and forward() will immediately fail when entries and events are disabled
  739. // (since there are no entries to traverse to), and if our starting point is instead navigate() or reload(),
  740. // then we avoided setting the upcoming non-traverse API method tracker in the first place.
  741. if (has_entries_and_events_disabled()) {
  742. // 1. Assert: navigation's ongoing API method tracker is null.
  743. VERIFY(m_ongoing_api_method_tracker == nullptr);
  744. // 2. Assert: navigation's upcoming non-traverse API method tracker is null.
  745. VERIFY(m_upcoming_non_traverse_api_method_tracker == nullptr);
  746. // 3. Assert: navigation's upcoming traverse API method trackers is empty.
  747. VERIFY(m_upcoming_traverse_api_method_trackers.is_empty());
  748. // 4. Return true.
  749. return true;
  750. }
  751. // 2. Let destinationKey be null.
  752. Optional<String> destination_key = {};
  753. // 3. If destination's entry is non-null, then set destinationKey to destination's entry's key.
  754. if (destination->navigation_history_entry() != nullptr)
  755. destination_key = destination->navigation_history_entry()->key();
  756. // 4. Assert: destinationKey is not the empty string.
  757. VERIFY(destination_key != ""sv);
  758. // 5. Promote an upcoming API method tracker to ongoing given navigation and destinationKey.
  759. promote_an_upcoming_api_method_tracker_to_ongoing(destination_key);
  760. // 6. Let apiMethodTracker be navigation's ongoing API method tracker.
  761. auto api_method_tracker = m_ongoing_api_method_tracker;
  762. // 7. Let navigable be navigation's relevant global object's navigable.
  763. auto& relevant_global_object = verify_cast<HTML::Window>(Web::HTML::relevant_global_object(*this));
  764. auto navigable = relevant_global_object.navigable();
  765. // 8. Let document be navigation's relevant global object's associated Document.
  766. auto& document = relevant_global_object.associated_document();
  767. // Note: We create the Event in this algorithm instead of passing it in,
  768. // and have all the following "initialize" steps set up the event init
  769. NavigateEventInit event_init = {};
  770. // 9. If document can have its URL rewritten to destination's URL,
  771. // and either destination's is same document is true or navigationType is not "traverse",
  772. // then initialize event's canIntercept to true. Otherwise, initialize it to false.
  773. event_init.can_intercept = can_have_its_url_rewritten(document, destination->raw_url()) && (destination->same_document() || navigation_type != Bindings::NavigationType::Traverse);
  774. // 10. Let traverseCanBeCanceled be true if all of the following are true:
  775. // - navigable is a top-level traversable;
  776. // - destination's is same document is true; and
  777. // - either userInvolvement is not "browser UI", or navigation's relevant global object has transient activation.
  778. // Otherwise, let it be false.
  779. bool const traverse_can_be_canceled = navigable->is_top_level_traversable()
  780. && destination->same_document()
  781. && (user_involvement != UserNavigationInvolvement::BrowserUI || relevant_global_object.has_transient_activation());
  782. // FIXME: Fix spec grammaro, extra 'the -> set'
  783. // 11. If either:
  784. // - navigationType is not "traverse"; or
  785. // - traverseCanBeCanceled is true
  786. // the initialize event's cancelable to true. Otherwise, initialize it to false.
  787. event_init.cancelable = (navigation_type != Bindings::NavigationType::Traverse) || traverse_can_be_canceled;
  788. // 12. Initialize event's type to "navigate".
  789. // AD-HOC: Happens later, when calling the factory function
  790. // 13. Initialize event's navigationType to navigationType.
  791. event_init.navigation_type = navigation_type;
  792. // 14. Initialize event's destination to destination.
  793. event_init.destination = destination;
  794. // 15. Initialize event's downloadRequest to downloadRequestFilename.
  795. event_init.download_request = move(download_request_filename);
  796. // 16. If apiMethodTracker is not null, then initialize event's info to apiMethodTracker's info. Otherwise, initialize it to undefined.
  797. // 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.
  798. if (api_method_tracker) {
  799. event_init.info = api_method_tracker->info;
  800. api_method_tracker->info = JS::js_undefined();
  801. } else {
  802. event_init.info = JS::js_undefined();
  803. }
  804. // FIXME: 17: Initialize event's hasUAVisualTransition to true if a visual transition, to display a cached rendered state
  805. // of the document's latest entry, was done by the user agent. Otherwise, initialize it to false.
  806. event_init.has_ua_visual_transition = false;
  807. // 18. Set event's abort controller to a new AbortController created in navigation's relevant realm.
  808. // AD-HOC: Set on the NavigateEvent later after construction
  809. auto abort_controller = MUST(DOM::AbortController::construct_impl(realm));
  810. // 19. Initialize event's signal to event's abort controller's signal.
  811. event_init.signal = abort_controller->signal();
  812. // 20. Let currentURL be document's URL.
  813. auto current_url = document.url();
  814. // 21. If all of the following are true:
  815. // - destination's is same document is true;
  816. // - destination's URL equals currentURL with exclude fragments set to true; and
  817. // - destination's URL's fragment is not identical to currentURL's fragment,
  818. // then initialize event's hashChange to true. Otherwise, initialize it to false.
  819. event_init.hash_change = (destination->same_document()
  820. && destination->raw_url().equals(current_url, URL::ExcludeFragment::Yes)
  821. && destination->raw_url().fragment() != current_url.fragment());
  822. // 22. If userInvolvement is not "none", then initialize event's userInitiated to true. Otherwise, initialize it to false.
  823. event_init.user_initiated = user_involvement != UserNavigationInvolvement::None;
  824. // 23. If formDataEntryList is not null, then initialize event's formData to a new FormData created in navigation's relevant realm,
  825. // associated to formDataEntryList. Otherwise, initialize it to null.
  826. if (form_data_entry_list.has_value()) {
  827. event_init.form_data = MUST(XHR::FormData::construct_impl(realm, form_data_entry_list.release_value()));
  828. } else {
  829. event_init.form_data = nullptr;
  830. }
  831. // AD-HOC: *Now* we have all the info required to create the event
  832. auto event = NavigateEvent::construct_impl(realm, EventNames::navigate, event_init);
  833. event->set_abort_controller(abort_controller);
  834. // AD-HOC: This is supposed to be set in "fire a <type> navigate event", and is only non-null when
  835. // we're doing a push or replace. We set it here because we create the event here
  836. event->set_classic_history_api_state(move(classic_history_api_state));
  837. // 24. Assert: navigation's ongoing navigate event is null.
  838. VERIFY(m_ongoing_navigate_event == nullptr);
  839. // 25. Set navigation's ongoing navigate event to event.
  840. m_ongoing_navigate_event = event;
  841. // 26. Set navigation's focus changed during ongoing navigation to false.
  842. m_focus_changed_during_ongoing_navigation = false;
  843. // 27. Set navigation's suppress normal scroll restoration during ongoing navigation to false.
  844. m_suppress_scroll_restoration_during_ongoing_navigation = false;
  845. // 28. Let dispatchResult be the result of dispatching event at navigation.
  846. auto dispatch_result = dispatch_event(*event);
  847. // 29. If dispatchResult is false:
  848. if (!dispatch_result) {
  849. // FIXME: 1. If navigationType is "traverse", then consume history-action user activation.
  850. // 2. If event's abort controller's signal is not aborted, then abort the ongoing navigation given navigation.
  851. if (!event->abort_controller()->signal()->aborted())
  852. abort_the_ongoing_navigation();
  853. // 3. Return false.
  854. return false;
  855. }
  856. // 30. Let endResultIsSameDocument be true if event's interception state
  857. // is not "none" or event's destination's is same document is true.
  858. bool const end_result_is_same_document = (event->interception_state() != NavigateEvent::InterceptionState::None) || event->destination()->same_document();
  859. // 31. Prepare to run script given navigation's relevant settings object.
  860. // NOTE: There's a massive spec note here
  861. TemporaryExecutionContext execution_context { relevant_settings_object(*this), TemporaryExecutionContext::CallbacksEnabled::Yes };
  862. // 32. If event's interception state is not "none":
  863. if (event->interception_state() != NavigateEvent::InterceptionState::None) {
  864. // 1. Set event's interception state to "committed".
  865. event->set_interception_state(NavigateEvent::InterceptionState::Committed);
  866. // 2. Let fromNHE be the current entry of navigation.
  867. auto from_nhe = current_entry();
  868. // 3. Assert: fromNHE is not null.
  869. VERIFY(from_nhe != nullptr);
  870. // 4. Set navigation's transition to a new NavigationTransition created in navigation's relevant realm,
  871. // whose navigation type is navigationType, from entry is fromNHE, and whose finished promise is a new promise
  872. // created in navigation's relevant realm.
  873. m_transition = NavigationTransition::create(realm, navigation_type, *from_nhe, JS::Promise::create(realm));
  874. // 5. Mark as handled navigation's transition's finished promise.
  875. m_transition->finished()->set_is_handled();
  876. // 6. If navigationType is "traverse", then set navigation's suppress normal scroll restoration during ongoing navigation to true.
  877. // NOTE: If event's scroll behavior was set to "after-transition", then scroll restoration will happen as part of finishing
  878. // the relevant NavigateEvent. Otherwise, there will be no scroll restoration. That is, no navigation which is intercepted
  879. // by intercept() goes through the normal scroll restoration process; scroll restoration for such navigations
  880. // is either done manually, by the web developer, or is done after the transition.
  881. if (navigation_type == Bindings::NavigationType::Traverse)
  882. m_suppress_scroll_restoration_during_ongoing_navigation = true;
  883. // FIXME: Fix spec typo "serialied"
  884. // 7. If navigationType is "push" or "replace", then run the URL and history update steps given document and
  885. // event's destination's URL, with serialiedData set to event's classic history API state and historyHandling
  886. // set to navigationType.
  887. if (navigation_type == Bindings::NavigationType::Push || navigation_type == Bindings::NavigationType::Replace) {
  888. auto history_handling = navigation_type == Bindings::NavigationType::Push ? HistoryHandlingBehavior::Push : HistoryHandlingBehavior::Replace;
  889. perform_url_and_history_update_steps(document, event->destination()->raw_url(), event->classic_history_api_state(), history_handling);
  890. }
  891. // Big spec note about reload here
  892. }
  893. // 33. If endResultIsSameDocument is true:
  894. if (end_result_is_same_document) {
  895. // 1. Let promisesList be an empty list.
  896. JS::MarkedVector<JS::NonnullGCPtr<WebIDL::Promise>> promises_list(realm.heap());
  897. // 2. For each handler of event's navigation handler list:
  898. for (auto const& handler : event->navigation_handler_list()) {
  899. // 1. Append the result of invoking handler with an empty arguments list to promisesList.
  900. auto result = WebIDL::invoke_callback(handler, {});
  901. // This *should* be equivalent to converting a promise to a promise capability
  902. promises_list.append(WebIDL::create_resolved_promise(realm, result.value().value()));
  903. }
  904. // 3. If promisesList's size is 0, then set promisesList to « a promise resolved with undefined ».
  905. // NOTE: There is a subtle timing difference between how waiting for all schedules its success and failure
  906. // steps when given zero promises versus ≥1 promises. For most uses of waiting for all, this does not matter.
  907. // However, with this API, there are so many events and promise handlers which could fire around the same time
  908. // that the difference is pretty easily observable: it can cause the event/promise handler sequence to vary.
  909. // (Some of the events and promises involved include: navigatesuccess / navigateerror, currententrychange,
  910. // dispose, apiMethodTracker's promises, and the navigation.transition.finished promise.)
  911. if (promises_list.size() == 0) {
  912. promises_list.append(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  913. }
  914. // 4. Wait for all of promisesList, with the following success steps:
  915. WebIDL::wait_for_all(
  916. realm, promises_list, [event, this, api_method_tracker](auto const&) -> void {
  917. // FIXME: Spec issue: Event's relevant global objects' *associated document*
  918. // 1. If event's relevant global object is not fully active, then abort these steps.
  919. auto& relevant_global_object = verify_cast<HTML::Window>(HTML::relevant_global_object(*event));
  920. auto& realm = event->realm();
  921. if (!relevant_global_object.associated_document().is_fully_active())
  922. return;
  923. // 2. If event's abort controller's signal is aborted, then abort these steps.
  924. if (event->abort_controller()->signal()->aborted())
  925. return;
  926. // 3. Assert: event equals navigation's ongoing navigate event.
  927. VERIFY(event == m_ongoing_navigate_event);
  928. // 4. Set navigation's ongoing navigate event to null.
  929. m_ongoing_navigate_event = nullptr;
  930. // 5. Finish event given true.
  931. event->finish(true);
  932. // FIXME: Implement https://dom.spec.whatwg.org/#concept-event-fire somewhere
  933. // 6. Fire an event named navigatesuccess at navigation.
  934. dispatch_event(DOM::Event::create(realm, EventNames::navigatesuccess));
  935. // 7. If navigation's transition is not null, then resolve navigation's transition's finished promise with undefined.
  936. if (m_transition != nullptr)
  937. m_transition->finished()->fulfill(JS::js_undefined());
  938. // 8. Set navigation's transition to null.
  939. m_transition = nullptr;
  940. // 9. If apiMethodTracker is non-null, then resolve the finished promise for apiMethodTracker.
  941. if (api_method_tracker != nullptr)
  942. resolve_the_finished_promise(*api_method_tracker); },
  943. // and the following failure steps given reason rejectionReason:
  944. [event, this, api_method_tracker](JS::Value rejection_reason) -> void {
  945. // FIXME: Spec issue: Event's relevant global objects' *associated document*
  946. // 1. If event's relevant global object is not fully active, then abort these steps.
  947. auto& relevant_global_object = verify_cast<HTML::Window>(HTML::relevant_global_object(*event));
  948. auto& realm = event->realm();
  949. if (!relevant_global_object.associated_document().is_fully_active())
  950. return;
  951. // 2. If event's abort controller's signal is aborted, then abort these steps.
  952. if (event->abort_controller()->signal()->aborted())
  953. return;
  954. // 3. Assert: event equals navigation's ongoing navigate event.
  955. VERIFY(event == m_ongoing_navigate_event);
  956. // 4. Set navigation's ongoing navigate event to null.
  957. m_ongoing_navigate_event = nullptr;
  958. // 5. Finish event given false.
  959. event->finish(false);
  960. // 6. Fire an event named navigateerror at navigation using ErrorEvent, with error initialized to rejectionReason, and message,
  961. // filename, lineno, and colno initialized to appropriate values that can be extracted from rejectionReason in the same
  962. // underspecified way that the report the exception algorithm does.
  963. ErrorEventInit event_init = {};
  964. event_init.error = rejection_reason;
  965. // FIXME: Extract information from the exception and the JS context in the wishy-washy way the spec says here.
  966. event_init.filename = String {};
  967. event_init.colno = 0;
  968. event_init.lineno = 0;
  969. event_init.message = String {};
  970. dispatch_event(ErrorEvent::create(realm, EventNames::navigateerror, event_init));
  971. // 7. If navigation's transition is not null, then reject navigation's transition's finished promise with rejectionReason.
  972. if (m_transition)
  973. m_transition->finished()->reject(rejection_reason);
  974. // 8. Set navigation's transition to null.
  975. m_transition = nullptr;
  976. // 9. If apiMethodTracker is non-null, then reject the finished promise for apiMethodTracker with rejectionReason.
  977. if (api_method_tracker != nullptr)
  978. reject_the_finished_promise(*api_method_tracker, rejection_reason);
  979. });
  980. }
  981. // 34. Otherwise, if apiMethodTracker is non-null, then clean up apiMethodTracker.
  982. else if (api_method_tracker != nullptr) {
  983. clean_up(*api_method_tracker);
  984. }
  985. // 35. Clean up after running script given navigation's relevant settings object.
  986. // Handled by TemporaryExecutionContext destructor from step 31
  987. // 36. If event's interception state is "none", then return true.
  988. // 37. Return false.
  989. return event->interception_state() == NavigateEvent::InterceptionState::None;
  990. }
  991. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#fire-a-traverse-navigate-event
  992. bool Navigation::fire_a_traverse_navigate_event(JS::NonnullGCPtr<SessionHistoryEntry> destination_she, UserNavigationInvolvement user_involvement)
  993. {
  994. auto& realm = relevant_realm(*this);
  995. auto& vm = this->vm();
  996. // 1. Let event be the result of creating an event given NavigateEvent, in navigation's relevant realm.
  997. // 2. Set event's classic history API state to null.
  998. // AD-HOC: These are handled in the inner algorithm
  999. // 3. Let destination be a new NavigationDestination created in navigation's relevant realm.
  1000. auto destination = NavigationDestination::create(realm);
  1001. // 4. Set destination's URL to destinationSHE's URL.
  1002. destination->set_url(destination_she->url);
  1003. // 5. Let destinationNHE be the NavigationHistoryEntry in navigation's entry list whose session history entry is destinationSHE,
  1004. // or null if no such NavigationHistoryEntry exists.
  1005. auto destination_nhe = m_entry_list.find_if([destination_she](auto& nhe) {
  1006. return &nhe->session_history_entry() == destination_she;
  1007. });
  1008. // 6. If destinationNHE is non-null, then:
  1009. if (destination_nhe != m_entry_list.end()) {
  1010. // 1. Set destination's entry to destinationNHE.
  1011. destination->set_entry(*destination_nhe);
  1012. // 2. Set destination's state to destinationSHE's navigation API state.
  1013. destination->set_state(destination_she->navigation_api_state);
  1014. }
  1015. // 7. Otherwise:
  1016. else {
  1017. // 1. Set destination's entry to null.
  1018. destination->set_entry(nullptr);
  1019. // 2. Set destination's state to StructuredSerializeForStorage(null).
  1020. destination->set_state(MUST(structured_serialize_for_storage(vm, JS::js_null())));
  1021. }
  1022. // 8. Set destination's is same document to true if destinationSHE's document is equal to
  1023. // navigation's relevant global object's associated Document; otherwise false.
  1024. destination->set_is_same_document(destination_she->document_state->document() == &verify_cast<Window>(relevant_global_object(*this)).associated_document());
  1025. // 9. Return the result of performing the inner navigate event firing algorithm given navigation, "traverse", event, destination, userInvolvement, null, and null.
  1026. // AD-HOC: We don't pass the event, but we do pass the classic_history_api state at the end to be set later
  1027. return inner_navigate_event_firing_algorithm(Bindings::NavigationType::Traverse, destination, user_involvement, {}, {}, {});
  1028. }
  1029. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#fire-a-push/replace/reload-navigate-event
  1030. bool Navigation::fire_a_push_replace_reload_navigate_event(
  1031. Bindings::NavigationType navigation_type,
  1032. URL destination_url,
  1033. bool is_same_document,
  1034. UserNavigationInvolvement user_involvement,
  1035. Optional<Vector<XHR::FormDataEntry>&> form_data_entry_list,
  1036. Optional<SerializationRecord> navigation_api_state,
  1037. Optional<SerializationRecord> classic_history_api_state)
  1038. {
  1039. auto& realm = relevant_realm(*this);
  1040. auto& vm = this->vm();
  1041. // This fulfills the entry requirement: an optional serialized state navigationAPIState (default StructuredSerializeForStorage(null))
  1042. if (!navigation_api_state.has_value())
  1043. navigation_api_state = MUST(structured_serialize_for_storage(vm, JS::js_null()));
  1044. // 1. Let event be the result of creating an event given NavigateEvent, in navigation's relevant realm.
  1045. // 2. Set event's classic history API state to classicHistoryAPIState.
  1046. // AD-HOC: These are handled in the inner algorithm
  1047. // 3. Let destination be a new NavigationDestination created in navigation's relevant realm.
  1048. auto destination = NavigationDestination::create(realm);
  1049. // 4. Set destination's URL to destinationURL.
  1050. destination->set_url(destination_url);
  1051. // 5. Set destination's entry to null.
  1052. destination->set_entry(nullptr);
  1053. // 6. Set destination's state to navigationAPIState.
  1054. destination->set_state(*navigation_api_state);
  1055. // 7. Set destination's is same document to isSameDocument.
  1056. destination->set_is_same_document(is_same_document);
  1057. // 8. Return the result of performing the inner navigate event firing algorithm given navigation,
  1058. // navigationType, event, destination, userInvolvement, formDataEntryList, and null.
  1059. // AD-HOC: We don't pass the event, but we do pass the classic_history_api state at the end to be set later
  1060. return inner_navigate_event_firing_algorithm(navigation_type, destination, user_involvement, move(form_data_entry_list), {}, move(classic_history_api_state));
  1061. }
  1062. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#fire-a-download-request-navigate-event
  1063. bool Navigation::fire_a_download_request_navigate_event(URL destination_url, UserNavigationInvolvement user_involvement, String filename)
  1064. {
  1065. auto& realm = relevant_realm(*this);
  1066. auto& vm = this->vm();
  1067. // 1. Let event be the result of creating an event given NavigateEvent, in navigation's relevant realm.
  1068. // 2. Set event's classic history API state to classicHistoryAPIState.
  1069. // AD-HOC: These are handled in the inner algorithm
  1070. // 3. Let destination be a new NavigationDestination created in navigation's relevant realm.
  1071. auto destination = NavigationDestination::create(realm);
  1072. // 4. Set destination's URL to destinationURL.
  1073. destination->set_url(destination_url);
  1074. // 5. Set destination's entry to null.
  1075. destination->set_entry(nullptr);
  1076. // 6. Set destination's state to StructuredSerializeForStorage(null).
  1077. destination->set_state(MUST(structured_serialize_for_storage(vm, JS::js_null())));
  1078. // 7. Set destination's is same document to false.
  1079. destination->set_is_same_document(false);
  1080. // 8. Return the result of performing the inner navigate event firing algorithm given navigation,
  1081. // "push", event, destination, userInvolvement, null, and filename.
  1082. // AD-HOC: We don't pass the event, but we do pass the classic_history_api state at the end to be set later
  1083. return inner_navigate_event_firing_algorithm(Bindings::NavigationType::Push, destination, user_involvement, {}, move(filename), {});
  1084. }
  1085. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#initialize-the-navigation-api-entries-for-a-new-document
  1086. void Navigation::initialize_the_navigation_api_entries_for_a_new_document(Vector<JS::NonnullGCPtr<SessionHistoryEntry>> const& new_shes, JS::NonnullGCPtr<SessionHistoryEntry> initial_she)
  1087. {
  1088. auto& realm = relevant_realm(*this);
  1089. // 1. Assert: navigation's entry list is empty.
  1090. VERIFY(m_entry_list.is_empty());
  1091. // 2. Assert: navigation's current entry index is −1.
  1092. VERIFY(m_current_entry_index == -1);
  1093. // 3. If navigation has entries and events disabled, then return.
  1094. if (has_entries_and_events_disabled())
  1095. return;
  1096. // 4. For each newSHE of newSHEs:
  1097. for (auto const& new_she : new_shes) {
  1098. // 1. Let newNHE be a new NavigationHistoryEntry created in the relevant realm of navigation.
  1099. // 2. Set newNHE's session history entry to newSHE.
  1100. auto new_nhe = NavigationHistoryEntry::create(realm, new_she);
  1101. // 3. Append newNHE to navigation's entry list.
  1102. m_entry_list.append(new_nhe);
  1103. }
  1104. // 5. Set navigation's current entry index to the result of getting the navigation API entry index of initialSHE within navigation.
  1105. m_current_entry_index = get_the_navigation_api_entry_index(*initial_she);
  1106. }
  1107. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#update-the-navigation-api-entries-for-a-same-document-navigation
  1108. void Navigation::update_the_navigation_api_entries_for_a_same_document_navigation(JS::NonnullGCPtr<SessionHistoryEntry> destination_she, Bindings::NavigationType navigation_type)
  1109. {
  1110. auto& realm = relevant_realm(*this);
  1111. // 1. If navigation has entries and events disabled, then return.
  1112. if (has_entries_and_events_disabled())
  1113. return;
  1114. // 2. Let oldCurrentNHE be the current entry of navigation.
  1115. auto old_current_nhe = current_entry();
  1116. // 3. Let disposedNHEs be a new empty list.
  1117. Vector<JS::NonnullGCPtr<NavigationHistoryEntry>> disposed_nhes;
  1118. // 4. If navigationType is "traverse", then:
  1119. if (navigation_type == Bindings::NavigationType::Traverse) {
  1120. // 1. Set navigation's current entry index to the result of getting the navigation API entry index of destinationSHE within navigation.
  1121. m_current_entry_index = get_the_navigation_api_entry_index(destination_she);
  1122. // 2. Assert: navigation's current entry index is not −1.
  1123. // NOTE: This algorithm is only called for same-document traversals.
  1124. // Cross-document traversals will instead call either initialize the navigation API entries for a new document
  1125. // or update the navigation API entries for reactivation
  1126. VERIFY(m_current_entry_index != -1);
  1127. }
  1128. // 5. Otherwise, if navigationType is "push", then:
  1129. else if (navigation_type == Bindings::NavigationType::Push) {
  1130. // 1. Set navigation's current entry index to navigation's current entry index + 1.
  1131. m_current_entry_index++;
  1132. // 2. Let i be navigation's current entry index.
  1133. auto i = m_current_entry_index;
  1134. // 3. While i < navigation's entry list's size:
  1135. while (i < static_cast<i64>(m_entry_list.size())) {
  1136. // 1. Append navigation's entry list[i] to disposedNHEs.
  1137. disposed_nhes.append(m_entry_list[i]);
  1138. // 2. Set i to i + 1.
  1139. ++i;
  1140. }
  1141. // 4. Remove all items in disposedNHEs from navigation's entry list.
  1142. m_entry_list.remove(m_current_entry_index, m_entry_list.size() - m_current_entry_index);
  1143. }
  1144. // 6. Otherwise, if navigationType is "replace", then:
  1145. else if (navigation_type == Bindings::NavigationType::Replace) {
  1146. VERIFY(old_current_nhe != nullptr);
  1147. // 1. Append oldCurrentNHE to disposedNHEs.
  1148. disposed_nhes.append(*old_current_nhe);
  1149. }
  1150. // 7. If navigationType is "push" or "replace", then:
  1151. if (navigation_type == Bindings::NavigationType::Push || navigation_type == Bindings::NavigationType::Replace) {
  1152. // 1. Let newNHE be a new NavigationHistoryEntry created in the relevant realm of navigation.
  1153. // 2. Set newNHE's session history entry to destinationSHE.
  1154. auto new_nhe = NavigationHistoryEntry::create(realm, destination_she);
  1155. VERIFY(m_current_entry_index != -1);
  1156. // 3. Set navigation's entry list[navigation's current entry index] to newNHE.
  1157. if (m_current_entry_index < static_cast<i64>(m_entry_list.size()))
  1158. m_entry_list[m_current_entry_index] = new_nhe;
  1159. else {
  1160. VERIFY(m_current_entry_index == static_cast<i64>(m_entry_list.size()));
  1161. m_entry_list.append(new_nhe);
  1162. }
  1163. }
  1164. // 8. If navigation's ongoing API method tracker is non-null, then notify about the committed-to entry
  1165. // given navigation's ongoing API method tracker and the current entry of navigation.
  1166. // NOTE: It is important to do this before firing the dispose or currententrychange events,
  1167. // since event handlers could start another navigation, or otherwise change the value of
  1168. // navigation's ongoing API method tracker.
  1169. if (m_ongoing_api_method_tracker != nullptr)
  1170. notify_about_the_committed_to_entry(*m_ongoing_api_method_tracker, *current_entry());
  1171. // 9. Prepare to run script given navigation's relevant settings object.
  1172. relevant_settings_object(*this).prepare_to_run_script();
  1173. // 10. Fire an event named currententrychange at navigation using NavigationCurrentEntryChangeEvent,
  1174. // with its navigationType attribute initialized to navigationType and its from initialized to oldCurrentNHE.
  1175. NavigationCurrentEntryChangeEventInit event_init = {};
  1176. event_init.navigation_type = navigation_type;
  1177. event_init.from = old_current_nhe;
  1178. dispatch_event(NavigationCurrentEntryChangeEvent::construct_impl(realm, EventNames::currententrychange, event_init));
  1179. // 11. For each disposedNHE of disposedNHEs:
  1180. for (auto& disposed_nhe : disposed_nhes) {
  1181. // 1. Fire an event named dispose at disposedNHE.
  1182. disposed_nhe->dispatch_event(DOM::Event::create(realm, EventNames::dispose, {}));
  1183. }
  1184. // 12. Clean up after running script given navigation's relevant settings object.
  1185. relevant_settings_object(*this).clean_up_after_running_script();
  1186. }
  1187. }