Navigation.cpp 75 KB

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