Navigation.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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/Document.h>
  13. #include <LibWeb/HTML/NavigateEvent.h>
  14. #include <LibWeb/HTML/Navigation.h>
  15. #include <LibWeb/HTML/NavigationCurrentEntryChangeEvent.h>
  16. #include <LibWeb/HTML/NavigationHistoryEntry.h>
  17. #include <LibWeb/HTML/NavigationTransition.h>
  18. #include <LibWeb/HTML/TraversableNavigable.h>
  19. #include <LibWeb/HTML/Window.h>
  20. namespace Web::HTML {
  21. static NavigationResult navigation_api_method_tracker_derived_result(JS::NonnullGCPtr<NavigationAPIMethodTracker> api_method_tracker);
  22. NavigationAPIMethodTracker::NavigationAPIMethodTracker(JS::NonnullGCPtr<Navigation> navigation,
  23. Optional<String> key,
  24. JS::Value info,
  25. Optional<SerializationRecord> serialized_state,
  26. JS::GCPtr<NavigationHistoryEntry> commited_to_entry,
  27. JS::NonnullGCPtr<WebIDL::Promise> committed_promise,
  28. JS::NonnullGCPtr<WebIDL::Promise> finished_promise)
  29. : navigation(navigation)
  30. , key(move(key))
  31. , info(info)
  32. , serialized_state(move(serialized_state))
  33. , commited_to_entry(commited_to_entry)
  34. , committed_promise(committed_promise)
  35. , finished_promise(finished_promise)
  36. {
  37. }
  38. void NavigationAPIMethodTracker::visit_edges(Cell::Visitor& visitor)
  39. {
  40. Base::visit_edges(visitor);
  41. visitor.visit(navigation);
  42. visitor.visit(info);
  43. visitor.visit(commited_to_entry);
  44. visitor.visit(committed_promise);
  45. visitor.visit(finished_promise);
  46. }
  47. JS::NonnullGCPtr<Navigation> Navigation::create(JS::Realm& realm)
  48. {
  49. return realm.heap().allocate<Navigation>(realm, realm);
  50. }
  51. Navigation::Navigation(JS::Realm& realm)
  52. : DOM::EventTarget(realm)
  53. {
  54. }
  55. Navigation::~Navigation() = default;
  56. void Navigation::initialize(JS::Realm& realm)
  57. {
  58. Base::initialize(realm);
  59. set_prototype(&Bindings::ensure_web_prototype<Bindings::NavigationPrototype>(realm, "Navigation"));
  60. }
  61. void Navigation::visit_edges(JS::Cell::Visitor& visitor)
  62. {
  63. Base::visit_edges(visitor);
  64. for (auto& entry : m_entry_list)
  65. visitor.visit(entry);
  66. visitor.visit(m_transition);
  67. visitor.visit(m_ongoing_navigate_event);
  68. visitor.visit(m_ongoing_api_method_tracker);
  69. visitor.visit(m_upcoming_non_traverse_api_method_tracker);
  70. for (auto& key_and_tracker : m_upcoming_traverse_api_method_trackers)
  71. visitor.visit(key_and_tracker.value);
  72. }
  73. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-entries
  74. Vector<JS::NonnullGCPtr<NavigationHistoryEntry>> Navigation::entries() const
  75. {
  76. // The entries() method steps are:
  77. // 1. If this has entries and events disabled, then return the empty list.
  78. if (has_entries_and_events_disabled())
  79. return {};
  80. // 2. Return this's entry list.
  81. // NOTE: Recall that because of Web IDL's sequence type conversion rules,
  82. // this will create a new JavaScript array object on each call.
  83. // That is, navigation.entries() !== navigation.entries().
  84. return m_entry_list;
  85. }
  86. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-current-entry
  87. JS::GCPtr<NavigationHistoryEntry> Navigation::current_entry() const
  88. {
  89. // The current entry of a Navigation navigation is the result of running the following steps:
  90. // 1. If navigation has entries and events disabled, then return null.
  91. if (has_entries_and_events_disabled())
  92. return nullptr;
  93. // FIXME 2. Assert: navigation's current entry index is not −1.
  94. // FIXME: This should not happen once Navigable's algorithms properly set up NHEs.
  95. if (m_current_entry_index == -1)
  96. return nullptr;
  97. // 3. Return navigation's entry list[navigation's current entry index].
  98. return m_entry_list[m_current_entry_index];
  99. }
  100. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-updatecurrententry
  101. WebIDL::ExceptionOr<void> Navigation::update_current_entry(NavigationUpdateCurrentEntryOptions options)
  102. {
  103. // The updateCurrentEntry(options) method steps are:
  104. // 1. Let current be the current entry of this.
  105. auto current = current_entry();
  106. // 2. If current is null, then throw an "InvalidStateError" DOMException.
  107. if (current == nullptr)
  108. return WebIDL::InvalidStateError::create(realm(), "Cannot update current NavigationHistoryEntry when there is no current entry"sv);
  109. // 3. Let serializedState be StructuredSerializeForStorage(options["state"]), rethrowing any exceptions.
  110. auto serialized_state = TRY(structured_serialize_for_storage(vm(), options.state));
  111. // 4. Set current's session history entry's navigation API state to serializedState.
  112. current->session_history_entry().navigation_api_state = serialized_state;
  113. // 5. Fire an event named currententrychange at this using NavigationCurrentEntryChangeEvent,
  114. // with its navigationType attribute initialized to null and its from initialized to current.
  115. NavigationCurrentEntryChangeEventInit event_init = {};
  116. event_init.navigation_type = {};
  117. event_init.from = current;
  118. dispatch_event(HTML::NavigationCurrentEntryChangeEvent::create(realm(), HTML::EventNames::currententrychange, event_init));
  119. return {};
  120. }
  121. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-cangoback
  122. bool Navigation::can_go_back() const
  123. {
  124. // The canGoBack getter steps are:
  125. // 1. If this has entries and events disabled, then return false.
  126. if (has_entries_and_events_disabled())
  127. return false;
  128. // FIXME 2. Assert: navigation's current entry index is not −1.
  129. // FIXME: This should not happen once Navigable's algorithms properly set up NHEs.
  130. if (m_current_entry_index == -1)
  131. return false;
  132. // 3. If this's current entry index is 0, then return false.
  133. // 4. Return true.
  134. return (m_current_entry_index != 0);
  135. }
  136. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-cangoforward
  137. bool Navigation::can_go_forward() const
  138. {
  139. // The canGoForward getter steps are:
  140. // 1. If this has entries and events disabled, then return false.
  141. if (has_entries_and_events_disabled())
  142. return false;
  143. // FIXME 2. Assert: navigation's current entry index is not −1.
  144. // FIXME: This should not happen once Navigable's algorithms properly set up NHEs.
  145. if (m_current_entry_index == -1)
  146. return false;
  147. // 3. If this's current entry index is equal to this's entry list's size, then return false.
  148. // 4. Return true.
  149. return (m_current_entry_index != static_cast<i64>(m_entry_list.size()));
  150. }
  151. static HistoryHandlingBehavior to_history_handling_behavior(Bindings::NavigationHistoryBehavior b)
  152. {
  153. switch (b) {
  154. case Bindings::NavigationHistoryBehavior::Auto:
  155. return HistoryHandlingBehavior::Default;
  156. case Bindings::NavigationHistoryBehavior::Push:
  157. return HistoryHandlingBehavior::Push;
  158. case Bindings::NavigationHistoryBehavior::Replace:
  159. return HistoryHandlingBehavior::Replace;
  160. };
  161. VERIFY_NOT_REACHED();
  162. }
  163. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-navigate
  164. WebIDL::ExceptionOr<NavigationResult> Navigation::navigate(String url, NavigationNavigateOptions const& options)
  165. {
  166. auto& realm = this->realm();
  167. auto& vm = this->vm();
  168. // The navigate(options) method steps are:
  169. // 1. Parse url relative to this's relevant settings object.
  170. // If that returns failure, then return an early error result for a "SyntaxError" DOMException.
  171. // Otherwise, let urlRecord be the resulting URL record.
  172. auto url_record = relevant_settings_object(*this).parse_url(url);
  173. if (!url_record.is_valid())
  174. return early_error_result(WebIDL::SyntaxError::create(realm, "Cannot navigate to Invalid URL"));
  175. // 2. Let document be this's relevant global object's associated Document.
  176. auto& document = verify_cast<HTML::Window>(relevant_global_object(*this)).associated_document();
  177. // 3. If options["history"] is "push", and the navigation must be a replace given urlRecord and document,
  178. // then return an early error result for a "NotSupportedError" DOMException.
  179. if (options.history == Bindings::NavigationHistoryBehavior::Push && navigation_must_be_a_replace(url_record, document))
  180. return early_error_result(WebIDL::NotSupportedError::create(realm, "Navigation must be a replace, but push was requested"));
  181. // 4. Let state be options["state"], if it exists; otherwise, undefined.
  182. auto state = options.state.value_or(JS::js_undefined());
  183. // 5. Let serializedState be StructuredSerializeForStorage(state).
  184. // If this throws an exception, then return an early error result for that exception.
  185. // FIXME: Fix this spec grammaro in the note
  186. // NOTE: It is importantly to perform this step early, since serialization can invoke web developer code,
  187. // which in turn might change various things we check in later steps.
  188. auto serialized_state_or_error = structured_serialize_for_storage(vm, state);
  189. if (serialized_state_or_error.is_error()) {
  190. return early_error_result(serialized_state_or_error.release_error());
  191. }
  192. auto serialized_state = serialized_state_or_error.release_value();
  193. // 6. If document is not fully active, then return an early error result for an "InvalidStateError" DOMException.
  194. if (!document.is_fully_active())
  195. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document is not fully active"));
  196. // 7. If document's unload counter is greater than 0, then return an early error result for an "InvalidStateError" DOMException.
  197. if (document.unload_counter() > 0)
  198. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document already unloaded"));
  199. // 8. Let info be options["info"], if it exists; otherwise, undefined.
  200. auto info = options.info.value_or(JS::js_undefined());
  201. // 9. Let apiMethodTracker be the result of maybe setting the upcoming non-traverse API method tracker for this
  202. // given info and serializedState.
  203. auto api_method_tracker = maybe_set_the_upcoming_non_traverse_api_method_tracker(info, serialized_state);
  204. // 10. Navigate document's node navigable to urlRecord using document,
  205. // with historyHandling set to options["history"] and navigationAPIState set to serializedState.
  206. // FIXME: Fix spec typo here
  207. // NOTE: Unlike location.assign() and friends, which are exposed across origin-domain boundaries,
  208. // navigation.navigate() can only be accessed by code with direct synchronous access to the
  209. /// window.navigation property. Thus, we avoid the complications about attributing the source document
  210. // of the navigation, and we don't need to deal with the allowed by sandboxing to navigate check and its
  211. // acccompanying exceptionsEnabled flag. We just treat all navigations as if they come from the Document
  212. // corresponding to this Navigation object itself (i.e., document).
  213. [[maybe_unused]] auto history_handling_behavior = to_history_handling_behavior(options.history);
  214. // FIXME: Actually call navigate once Navigables are implemented enough to guarantee a node navigable on
  215. // an active document that's not being unloaded.
  216. // document.navigable().navigate(url, document, history behavior, state)
  217. // 11. If this's upcoming non-traverse API method tracker is apiMethodTracker, then:
  218. // NOTE: If the upcoming non-traverse API method tracker is still apiMethodTracker, this means that the navigate
  219. // algorithm bailed out before ever getting to the inner navigate event firing algorithm which would promote
  220. // that upcoming API method tracker to ongoing.
  221. if (m_upcoming_non_traverse_api_method_tracker == api_method_tracker) {
  222. m_upcoming_non_traverse_api_method_tracker = nullptr;
  223. return early_error_result(WebIDL::AbortError::create(realm, "Navigation aborted"));
  224. }
  225. // 12. Return a navigation API method tracker-derived result for apiMethodTracker.
  226. return navigation_api_method_tracker_derived_result(api_method_tracker);
  227. }
  228. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-reload
  229. WebIDL::ExceptionOr<NavigationResult> Navigation::reload(NavigationReloadOptions const& options)
  230. {
  231. auto& realm = this->realm();
  232. auto& vm = this->vm();
  233. // The reload(options) method steps are:
  234. // 1. Let document be this's relevant global object's associated Document.
  235. auto& document = verify_cast<HTML::Window>(relevant_global_object(*this)).associated_document();
  236. // 2. Let serializedState be StructuredSerializeForStorage(undefined).
  237. auto serialized_state = MUST(structured_serialize_for_storage(vm, JS::js_undefined()));
  238. // 3. If options["state"] exists, then set serializedState to StructuredSerializeForStorage(options["state"]).
  239. // If this throws an exception, then return an early error result for that exception.
  240. // NOTE: It is importantly to perform this step early, since serialization can invoke web developer
  241. // code, which in turn might change various things we check in later steps.
  242. if (options.state.has_value()) {
  243. auto serialized_state_or_error = structured_serialize_for_storage(vm, options.state.value());
  244. if (serialized_state_or_error.is_error())
  245. return early_error_result(serialized_state_or_error.release_error());
  246. serialized_state = serialized_state_or_error.release_value();
  247. }
  248. // 4. Otherwise:
  249. else {
  250. // 1. Let current be the current entry of this.
  251. auto current = current_entry();
  252. // 2. If current is not null, then set serializedState to current's session history entry's navigation API state.
  253. if (current != nullptr)
  254. serialized_state = current->session_history_entry().navigation_api_state;
  255. }
  256. // 5. If document is not fully active, then return an early error result for an "InvalidStateError" DOMException.
  257. if (!document.is_fully_active())
  258. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document is not fully active"));
  259. // 6. If document's unload counter is greater than 0, then return an early error result for an "InvalidStateError" DOMException.
  260. if (document.unload_counter() > 0)
  261. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document already unloaded"));
  262. // 7. Let info be options["info"], if it exists; otherwise, undefined.
  263. auto info = options.info.value_or(JS::js_undefined());
  264. // 8. Let apiMethodTracker be the result of maybe setting the upcoming non-traverse API method tracker for this given info and serializedState.
  265. auto api_method_tracker = maybe_set_the_upcoming_non_traverse_api_method_tracker(info, serialized_state);
  266. // 9. Reload document's node navigable with navigationAPIState set to serializedState.
  267. // FIXME: Actually call reload once Navigables are implemented enough to guarantee a node navigable on
  268. // an active document that's not being unloaded.
  269. // document.navigable().reload(state)
  270. return navigation_api_method_tracker_derived_result(api_method_tracker);
  271. }
  272. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-traverseto
  273. WebIDL::ExceptionOr<NavigationResult> Navigation::traverse_to(String key, NavigationOptions const& options)
  274. {
  275. auto& realm = this->realm();
  276. // The traverseTo(key, options) method steps are:
  277. // 1. If this's current entry index is −1, then return an early error result for an "InvalidStateError" DOMException.
  278. if (m_current_entry_index == -1)
  279. return early_error_result(WebIDL::InvalidStateError::create(realm, "Cannot traverseTo: no current session history entry"));
  280. // 2. If this's entry list does not contain a NavigationHistoryEntry whose session history entry's navigation API key equals key,
  281. // then return an early error result for an "InvalidStateError" DOMException.
  282. auto it = m_entry_list.find_if([&key](auto const& entry) {
  283. return entry->session_history_entry().navigation_api_key == key;
  284. });
  285. if (it == m_entry_list.end())
  286. return early_error_result(WebIDL::InvalidStateError::create(realm, "Cannot traverseTo: key not found in session history list"));
  287. // 3. Return the result of performing a navigation API traversal given this, key, and options.
  288. return perform_a_navigation_api_traversal(key, options);
  289. }
  290. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#performing-a-navigation-api-traversal
  291. WebIDL::ExceptionOr<NavigationResult> Navigation::back(NavigationOptions const& options)
  292. {
  293. auto& realm = this->realm();
  294. // The back(options) method steps are:
  295. // 1. If this's current entry index is −1 or 0, then return an early error result for an "InvalidStateError" DOMException.
  296. if (m_current_entry_index == -1 || m_current_entry_index == 0)
  297. return early_error_result(WebIDL::InvalidStateError::create(realm, "Cannot navigate back: no previous session history entry"));
  298. // 2. Let key be this's entry list[this's current entry index − 1]'s session history entry's navigation API key.
  299. auto key = m_entry_list[m_current_entry_index - 1]->session_history_entry().navigation_api_key;
  300. // 3. Return the result of performing a navigation API traversal given this, key, and options.
  301. return perform_a_navigation_api_traversal(key, options);
  302. }
  303. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation-forward
  304. WebIDL::ExceptionOr<NavigationResult> Navigation::forward(NavigationOptions const& options)
  305. {
  306. auto& realm = this->realm();
  307. // The forward(options) method steps are:
  308. // 1. If this's current entry index is −1 or is equal to this's entry list's size − 1,
  309. // then return an early error result for an "InvalidStateError" DOMException.
  310. if (m_current_entry_index == -1 || m_current_entry_index == static_cast<i64>(m_entry_list.size() - 1))
  311. return early_error_result(WebIDL::InvalidStateError::create(realm, "Cannot navigate forward: no next session history entry"));
  312. // 2. Let key be this's entry list[this's current entry index + 1]'s session history entry's navigation API key.
  313. auto key = m_entry_list[m_current_entry_index + 1]->session_history_entry().navigation_api_key;
  314. // 3. Return the result of performing a navigation API traversal given this, key, and options.
  315. return perform_a_navigation_api_traversal(key, options);
  316. }
  317. void Navigation::set_onnavigate(WebIDL::CallbackType* event_handler)
  318. {
  319. set_event_handler_attribute(HTML::EventNames::navigate, event_handler);
  320. }
  321. WebIDL::CallbackType* Navigation::onnavigate()
  322. {
  323. return event_handler_attribute(HTML::EventNames::navigate);
  324. }
  325. void Navigation::set_onnavigatesuccess(WebIDL::CallbackType* event_handler)
  326. {
  327. set_event_handler_attribute(HTML::EventNames::navigatesuccess, event_handler);
  328. }
  329. WebIDL::CallbackType* Navigation::onnavigatesuccess()
  330. {
  331. return event_handler_attribute(HTML::EventNames::navigatesuccess);
  332. }
  333. void Navigation::set_onnavigateerror(WebIDL::CallbackType* event_handler)
  334. {
  335. set_event_handler_attribute(HTML::EventNames::navigateerror, event_handler);
  336. }
  337. WebIDL::CallbackType* Navigation::onnavigateerror()
  338. {
  339. return event_handler_attribute(HTML::EventNames::navigateerror);
  340. }
  341. void Navigation::set_oncurrententrychange(WebIDL::CallbackType* event_handler)
  342. {
  343. set_event_handler_attribute(HTML::EventNames::currententrychange, event_handler);
  344. }
  345. WebIDL::CallbackType* Navigation::oncurrententrychange()
  346. {
  347. return event_handler_attribute(HTML::EventNames::currententrychange);
  348. }
  349. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#has-entries-and-events-disabled
  350. bool Navigation::has_entries_and_events_disabled() const
  351. {
  352. // A Navigation navigation has entries and events disabled if the following steps return true:
  353. // 1. Let document be navigation's relevant global object's associated Document.
  354. auto const& document = verify_cast<HTML::Window>(relevant_global_object(*this)).associated_document();
  355. // 2. If document is not fully active, then return true.
  356. if (!document.is_fully_active())
  357. return true;
  358. // 3. If document's is initial about:blank is true, then return true.
  359. if (document.is_initial_about_blank())
  360. return true;
  361. // 4. If document's origin is opaque, then return true.
  362. if (document.origin().is_opaque())
  363. return true;
  364. // 5. Return false.
  365. return false;
  366. }
  367. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#getting-the-navigation-api-entry-index
  368. i64 Navigation::get_the_navigation_api_entry_index(SessionHistoryEntry const& she) const
  369. {
  370. // To get the navigation API entry index of a session history entry she within a Navigation navigation:
  371. // 1. Let index be 0.
  372. i64 index = 0;
  373. // 2. For each nhe of navigation's entry list:
  374. for (auto const& nhe : m_entry_list) {
  375. // 1. If nhe's session history entry is equal to she, then return index.
  376. if (&nhe->session_history_entry() == &she)
  377. return index;
  378. // 2. Increment index by 1.
  379. ++index;
  380. }
  381. // 3. Return −1.
  382. return -1;
  383. }
  384. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-api-early-error-result
  385. NavigationResult Navigation::early_error_result(AnyException e)
  386. {
  387. auto& vm = this->vm();
  388. // An early error result for an exception e is a NavigationResult dictionary instance given by
  389. // «[ "committed" → a promise rejected with e, "finished" → a promise rejected with e ]».
  390. auto throw_completion = Bindings::dom_exception_to_throw_completion(vm, e);
  391. return {
  392. .committed = WebIDL::create_rejected_promise(realm(), *throw_completion.value())->promise(),
  393. .finished = WebIDL::create_rejected_promise(realm(), *throw_completion.value())->promise(),
  394. };
  395. }
  396. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigation-api-method-tracker-derived-result
  397. NavigationResult navigation_api_method_tracker_derived_result(JS::NonnullGCPtr<NavigationAPIMethodTracker> api_method_tracker)
  398. {
  399. // A navigation API method tracker-derived result for a navigation API method tracker is a NavigationResult
  400. /// dictionary instance given by «[ "committed" apiMethodTracker's committed promise, "finished" → apiMethodTracker's finished promise ]».
  401. return {
  402. api_method_tracker->committed_promise->promise(),
  403. api_method_tracker->finished_promise->promise(),
  404. };
  405. }
  406. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#upcoming-non-traverse-api-method-tracker
  407. JS::NonnullGCPtr<NavigationAPIMethodTracker> Navigation::maybe_set_the_upcoming_non_traverse_api_method_tracker(JS::Value info, Optional<SerializationRecord> serialized_state)
  408. {
  409. auto& realm = relevant_realm(*this);
  410. auto& vm = this->vm();
  411. // To maybe set the upcoming non-traverse API method tracker given a Navigation navigation,
  412. // a JavaScript value info, and a serialized state-or-null serializedState:
  413. // 1. Let committedPromise and finishedPromise be new promises created in navigation's relevant realm.
  414. auto committed_promise = WebIDL::create_promise(realm);
  415. auto finished_promise = WebIDL::create_promise(realm);
  416. // 2. Mark as handled finishedPromise.
  417. // NOTE: The web developer doesn’t necessarily care about finishedPromise being rejected:
  418. // - They might only care about committedPromise.
  419. // - They could be doing multiple synchronous navigations within the same task,
  420. // in which case all but the last will be aborted (causing their finishedPromise to reject).
  421. // This could be an application bug, but also could just be an emergent feature of disparate
  422. // parts of the application overriding each others' actions.
  423. // - They might prefer to listen to other transition-failure signals instead of finishedPromise, e.g.,
  424. // the navigateerror event, or the navigation.transition.finished promise.
  425. // As such, we mark it as handled to ensure that it never triggers unhandledrejection events.
  426. WebIDL::mark_promise_as_handled(finished_promise);
  427. // 3. Let apiMethodTracker be a new navigation API method tracker with:
  428. // navigation object: navigation
  429. // key: null
  430. // info: info
  431. // serialized state: serializedState
  432. // comitted-to entry: null
  433. // comitted promise: committedPromise
  434. // finished promise: finishedPromise
  435. auto api_method_tracker = vm.heap().allocate_without_realm<NavigationAPIMethodTracker>(
  436. /* .navigation = */ *this,
  437. /* .key = */ OptionalNone {},
  438. /* .info = */ info,
  439. /* .serialized_state = */ move(serialized_state),
  440. /* .commited_to_entry = */ nullptr,
  441. /* .committed_promise = */ committed_promise,
  442. /* .finished_promise = */ finished_promise);
  443. // 4. Assert: navigation's upcoming non-traverse API method tracker is null.
  444. VERIFY(m_upcoming_non_traverse_api_method_tracker == nullptr);
  445. // 5. If navigation does not have entries and events disabled,
  446. // then set navigation's upcoming non-traverse API method tracker to apiMethodTracker.
  447. // NOTE: If navigation has entries and events disabled, then committedPromise and finishedPromise will never fulfill
  448. // (since we never create a NavigationHistoryEntry object for such Documents, and so we have nothing to resolve them with);
  449. // there is no NavigationHistoryEntry to apply serializedState to; and there is no navigate event to include info with.
  450. // So, we don't need to track this API method call after all.
  451. if (!has_entries_and_events_disabled())
  452. m_upcoming_non_traverse_api_method_tracker = api_method_tracker;
  453. // 6. Return apiMethodTracker.
  454. return api_method_tracker;
  455. }
  456. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#add-an-upcoming-traverse-api-method-tracker
  457. JS::NonnullGCPtr<NavigationAPIMethodTracker> Navigation::add_an_upcoming_traverse_api_method_tracker(String destination_key, JS::Value info)
  458. {
  459. auto& vm = this->vm();
  460. auto& realm = relevant_realm(*this);
  461. // To add an upcoming traverse API method tracker given a Navigation navigation, a string destinationKey, and a JavaScript value info:
  462. // 1. Let committedPromise and finishedPromise be new promises created in navigation's relevant realm.
  463. auto committed_promise = WebIDL::create_promise(realm);
  464. auto finished_promise = WebIDL::create_promise(realm);
  465. // 2. Mark as handled finishedPromise.
  466. // NOTE: See the previous discussion about why this is done
  467. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#note-mark-as-handled-navigation-api-finished
  468. WebIDL::mark_promise_as_handled(*finished_promise);
  469. // 3. Let apiMethodTracker be a new navigation API method tracker with:
  470. // navigation object: navigation
  471. // key: destinationKey
  472. // info: info
  473. // serialized state: null
  474. // comitted-to entry: null
  475. // comitted promise: committedPromise
  476. // finished promise: finishedPromise
  477. auto api_method_tracker = vm.heap().allocate_without_realm<NavigationAPIMethodTracker>(
  478. /* .navigation = */ *this,
  479. /* .key = */ destination_key,
  480. /* .info = */ info,
  481. /* .serialized_state = */ OptionalNone {},
  482. /* .commited_to_entry = */ nullptr,
  483. /* .committed_promise = */ committed_promise,
  484. /* .finished_promise = */ finished_promise);
  485. // 4. Set navigation's upcoming traverse API method trackers[key] to apiMethodTracker.
  486. // FIXME: Fix spec typo key --> destinationKey
  487. m_upcoming_traverse_api_method_trackers.set(destination_key, api_method_tracker);
  488. // 5. Return apiMethodTracker.
  489. return api_method_tracker;
  490. }
  491. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#performing-a-navigation-api-traversal
  492. WebIDL::ExceptionOr<NavigationResult> Navigation::perform_a_navigation_api_traversal(String key, NavigationOptions const& options)
  493. {
  494. auto& realm = this->realm();
  495. // To perform a navigation API traversal given a Navigation navigation, a string key, and a NavigationOptions options:
  496. // 1. Let document be this's relevant global object's associated Document.
  497. auto& document = verify_cast<HTML::Window>(relevant_global_object(*this)).associated_document();
  498. // 2. If document is not fully active, then return an early error result for an "InvalidStateError" DOMException.
  499. if (!document.is_fully_active())
  500. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document is not fully active"));
  501. // 3. If document's unload counter is greater than 0, then return an early error result for an "InvalidStateError" DOMException.
  502. if (document.unload_counter() > 0)
  503. return early_error_result(WebIDL::InvalidStateError::create(realm, "Document already unloaded"));
  504. // 4. Let current be the current entry of navigation.
  505. auto current = current_entry();
  506. // 5. If key equals current's session history entry's navigation API key, then return
  507. // «[ "committed" → a promise resolved with current, "finished" → a promise resolved with current ]».
  508. if (key == current->session_history_entry().navigation_api_key) {
  509. return NavigationResult {
  510. .committed = WebIDL::create_resolved_promise(realm, current)->promise(),
  511. .finished = WebIDL::create_resolved_promise(realm, current)->promise()
  512. };
  513. }
  514. // 6. If navigation's upcoming traverse API method trackers[key] exists,
  515. // then return a navigation API method tracker-derived result for navigation's upcoming traverse API method trackers[key].
  516. if (auto maybe_tracker = m_upcoming_traverse_api_method_trackers.get(key); maybe_tracker.has_value())
  517. return navigation_api_method_tracker_derived_result(maybe_tracker.value());
  518. // 7. Let info be options["info"], if it exists; otherwise, undefined.
  519. auto info = options.info.value_or(JS::js_undefined());
  520. // 8. Let apiMethodTracker be the result of adding an upcoming traverse API method tracker for navigation given key and info.
  521. auto api_method_tracker = add_an_upcoming_traverse_api_method_tracker(key, info);
  522. // 9. Let navigable be document's node navigable.
  523. auto navigable = document.navigable();
  524. // 10. Let traversable be navigable's traversable navigable.
  525. auto traversable = navigable->traversable_navigable();
  526. // 11. Let sourceSnapshotParams be the result of snapshotting source snapshot params given document.
  527. auto source_snapshot_params = document.snapshot_source_snapshot_params();
  528. // 12. Append the following session history traversal steps to traversable:
  529. traversable->append_session_history_traversal_steps([key, api_method_tracker, navigable, source_snapshot_params, this] {
  530. // 1. Let navigableSHEs be the result of getting session history entries given navigable.
  531. auto navigable_shes = navigable->get_session_history_entries();
  532. // 2. Let targetSHE be the session history entry in navigableSHEs whose navigation API key is key. If no such entry exists, then:
  533. auto it = navigable_shes.find_if([&key](auto const& entry) {
  534. return entry->navigation_api_key == key;
  535. });
  536. if (it == navigable_shes.end()) {
  537. // NOTE: This path is taken if navigation's entry list was outdated compared to navigableSHEs,
  538. // which can occur for brief periods while all the relevant threads and processes are being synchronized in reaction to a history change.
  539. // 1. Queue a global task on the navigation and traversal task source given navigation's relevant global object
  540. // to reject the finished promise for apiMethodTracker with an "InvalidStateError" DOMException.
  541. queue_global_task(HTML::Task::Source::NavigationAndTraversal, relevant_global_object(*this), [this, api_method_tracker] {
  542. auto& reject_realm = relevant_realm(*this);
  543. WebIDL::reject_promise(reject_realm, api_method_tracker->finished_promise,
  544. WebIDL::InvalidStateError::create(reject_realm, "Cannot traverse with stale session history entry"));
  545. });
  546. // 2. Abort these steps.
  547. return;
  548. }
  549. auto target_she = *it;
  550. // 3. If targetSHE is navigable's active session history entry, then abort these steps.
  551. // NOTE: This can occur if a previously queued traversal already took us to this session history entry.
  552. // In that case the previous traversal will have dealt with apiMethodTracker already.
  553. if (target_she == navigable->active_session_history_entry())
  554. return;
  555. // FIXME: 4. Let result be the result of applying the traverse history step given by targetSHE's step to traversable,
  556. // given sourceSnapshotParams, navigable, and "none".
  557. (void)source_snapshot_params;
  558. // NOTE: When result is "canceled-by-beforeunload" or "initiator-disallowed", the navigate event was never fired,
  559. // aborting the ongoing navigation would not be correct; it would result in a navigateerror event without a
  560. // preceding navigate event. In the "canceled-by-navigate" case, navigate is fired, but the inner navigate event
  561. // firing algorithm will take care of aborting the ongoing navigation.
  562. // FIXME: 5. If result is "canceled-by-beforeunload", then queue a global task on the navigation and traversal task source
  563. // given navigation's relevant global object to reject the finished promise for apiMethodTracker with a
  564. // new "AbortError"DOMException created in navigation's relevant realm.
  565. // FIXME: 6. If result is "initiator-disallowed", then queue a global task on the navigation and traversal task source
  566. // given navigation's relevant global object to reject the finished promise for apiMethodTracker with a
  567. // new "SecurityError" DOMException created in navigation's relevant realm.
  568. });
  569. // 13. Return a navigation API method tracker-derived result for apiMethodTracker.
  570. return navigation_api_method_tracker_derived_result(api_method_tracker);
  571. }
  572. }