Navigation.cpp 77 KB

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