Navigation.cpp 66 KB

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