Navigation.cpp 34 KB

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