TraversableNavigable.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <LibWeb/Bindings/MainThreadVM.h>
  8. #include <LibWeb/DOM/Document.h>
  9. #include <LibWeb/HTML/BrowsingContextGroup.h>
  10. #include <LibWeb/HTML/DocumentState.h>
  11. #include <LibWeb/HTML/Navigation.h>
  12. #include <LibWeb/HTML/NavigationParams.h>
  13. #include <LibWeb/HTML/SessionHistoryEntry.h>
  14. #include <LibWeb/HTML/TraversableNavigable.h>
  15. #include <LibWeb/HTML/Window.h>
  16. #include <LibWeb/Page/Page.h>
  17. #include <LibWeb/Platform/EventLoopPlugin.h>
  18. namespace Web::HTML {
  19. JS_DEFINE_ALLOCATOR(TraversableNavigable);
  20. TraversableNavigable::TraversableNavigable(JS::NonnullGCPtr<Page> page)
  21. : m_page(page)
  22. {
  23. }
  24. TraversableNavigable::~TraversableNavigable() = default;
  25. void TraversableNavigable::visit_edges(Cell::Visitor& visitor)
  26. {
  27. Base::visit_edges(visitor);
  28. visitor.visit(m_page);
  29. for (auto& entry : m_session_history_entries)
  30. visitor.visit(entry);
  31. }
  32. static OrderedHashTable<TraversableNavigable*>& user_agent_top_level_traversable_set()
  33. {
  34. static OrderedHashTable<TraversableNavigable*> set;
  35. return set;
  36. }
  37. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-top-level-browsing-context
  38. WebIDL::ExceptionOr<BrowsingContextAndDocument> create_a_new_top_level_browsing_context_and_document(JS::NonnullGCPtr<Page> page)
  39. {
  40. // 1. Let group and document be the result of creating a new browsing context group and document.
  41. auto [group, document] = TRY(BrowsingContextGroup::create_a_new_browsing_context_group_and_document(page));
  42. // 2. Return group's browsing context set[0] and document.
  43. return BrowsingContextAndDocument { **group->browsing_context_set().begin(), document };
  44. }
  45. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-top-level-traversable
  46. WebIDL::ExceptionOr<JS::NonnullGCPtr<TraversableNavigable>> TraversableNavigable::create_a_new_top_level_traversable(JS::NonnullGCPtr<Page> page, JS::GCPtr<HTML::BrowsingContext> opener, String target_name)
  47. {
  48. auto& vm = Bindings::main_thread_vm();
  49. // 1. Let document be null.
  50. JS::GCPtr<DOM::Document> document = nullptr;
  51. // 2. If opener is null, then set document to the second return value of creating a new top-level browsing context and document.
  52. if (!opener) {
  53. document = TRY(create_a_new_top_level_browsing_context_and_document(page)).document;
  54. }
  55. // 3. Otherwise, set document to the second return value of creating a new auxiliary browsing context and document given opener.
  56. else {
  57. document = TRY(BrowsingContext::create_a_new_auxiliary_browsing_context_and_document(page, *opener)).document;
  58. }
  59. // 4. Let documentState be a new document state, with
  60. auto document_state = vm.heap().allocate_without_realm<DocumentState>();
  61. // document: document
  62. document_state->set_document(document);
  63. // initiator origin: null if opener is null; otherwise, document's origin
  64. document_state->set_initiator_origin(opener ? Optional<Origin> {} : document->origin());
  65. // origin: document's origin
  66. document_state->set_origin(document->origin());
  67. // navigable target name: targetName
  68. document_state->set_navigable_target_name(target_name);
  69. // about base URL: document's about base URL
  70. document_state->set_about_base_url(document->about_base_url());
  71. // 5. Let traversable be a new traversable navigable.
  72. auto traversable = vm.heap().allocate_without_realm<TraversableNavigable>(page);
  73. // 6. Initialize the navigable traversable given documentState.
  74. TRY_OR_THROW_OOM(vm, traversable->initialize_navigable(document_state, nullptr));
  75. // 7. Let initialHistoryEntry be traversable's active session history entry.
  76. auto initial_history_entry = traversable->active_session_history_entry();
  77. VERIFY(initial_history_entry);
  78. // 8. Set initialHistoryEntry's step to 0.
  79. initial_history_entry->step = 0;
  80. // 9. Append initialHistoryEntry to traversable's session history entries.
  81. traversable->m_session_history_entries.append(*initial_history_entry);
  82. // FIXME: 10. If opener is non-null, then legacy-clone a traversable storage shed given opener's top-level traversable and traversable. [STORAGE]
  83. // 11. Append traversable to the user agent's top-level traversable set.
  84. user_agent_top_level_traversable_set().set(traversable);
  85. // 12. Return traversable.
  86. return traversable;
  87. }
  88. // https://html.spec.whatwg.org/multipage/document-sequences.html#create-a-fresh-top-level-traversable
  89. WebIDL::ExceptionOr<JS::NonnullGCPtr<TraversableNavigable>> TraversableNavigable::create_a_fresh_top_level_traversable(JS::NonnullGCPtr<Page> page, AK::URL const& initial_navigation_url, Variant<Empty, String, POSTResource> initial_navigation_post_resource)
  90. {
  91. // 1. Let traversable be the result of creating a new top-level traversable given null and the empty string.
  92. auto traversable = TRY(create_a_new_top_level_traversable(page, nullptr, {}));
  93. // 2. Navigate traversable to initialNavigationURL using traversable's active document, with documentResource set to initialNavigationPostResource.
  94. TRY(traversable->navigate({ .url = initial_navigation_url,
  95. .source_document = *traversable->active_document(),
  96. .document_resource = initial_navigation_post_resource }));
  97. // 3. Return traversable.
  98. return traversable;
  99. }
  100. // https://html.spec.whatwg.org/multipage/document-sequences.html#top-level-traversable
  101. bool TraversableNavigable::is_top_level_traversable() const
  102. {
  103. // A top-level traversable is a traversable navigable with a null parent.
  104. return parent() == nullptr;
  105. }
  106. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-used-history-steps
  107. Vector<int> TraversableNavigable::get_all_used_history_steps() const
  108. {
  109. // FIXME: 1. Assert: this is running within traversable's session history traversal queue.
  110. // 2. Let steps be an empty ordered set of non-negative integers.
  111. OrderedHashTable<int> steps;
  112. // 3. Let entryLists be the ordered set « traversable's session history entries ».
  113. Vector<Vector<JS::NonnullGCPtr<SessionHistoryEntry>>> entry_lists { session_history_entries() };
  114. // 4. For each entryList of entryLists:
  115. while (!entry_lists.is_empty()) {
  116. auto entry_list = entry_lists.take_first();
  117. // 1. For each entry of entryList:
  118. for (auto& entry : entry_list) {
  119. // 1. Append entry's step to steps.
  120. steps.set(entry->step.get<int>());
  121. // 2. For each nestedHistory of entry's document state's nested histories, append nestedHistory's entries list to entryLists.
  122. for (auto& nested_history : entry->document_state->nested_histories())
  123. entry_lists.append(nested_history.entries);
  124. }
  125. }
  126. // 5. Return steps, sorted.
  127. auto sorted_steps = steps.values();
  128. quick_sort(sorted_steps);
  129. return sorted_steps;
  130. }
  131. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-history-object-length-and-index
  132. TraversableNavigable::HistoryObjectLengthAndIndex TraversableNavigable::get_the_history_object_length_and_index(int step) const
  133. {
  134. // 1. Let steps be the result of getting all used history steps within traversable.
  135. auto steps = get_all_used_history_steps();
  136. // 2. Let scriptHistoryLength be the size of steps.
  137. auto script_history_length = steps.size();
  138. // 3. Assert: steps contains step.
  139. VERIFY(steps.contains_slow(step));
  140. // 4. Let scriptHistoryIndex be the index of step in steps.
  141. auto script_history_index = *steps.find_first_index(step);
  142. // 5. Return (scriptHistoryLength, scriptHistoryIndex).
  143. return HistoryObjectLengthAndIndex {
  144. .script_history_length = script_history_length,
  145. .script_history_index = script_history_index
  146. };
  147. }
  148. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-used-step
  149. int TraversableNavigable::get_the_used_step(int step) const
  150. {
  151. // 1. Let steps be the result of getting all used history steps within traversable.
  152. auto steps = get_all_used_history_steps();
  153. // 2. Return the greatest item in steps that is less than or equal to step.
  154. VERIFY(!steps.is_empty());
  155. Optional<int> result;
  156. for (size_t i = 0; i < steps.size(); i++) {
  157. if (steps[i] <= step) {
  158. if (!result.has_value() || (result.value() < steps[i])) {
  159. result = steps[i];
  160. }
  161. }
  162. }
  163. return result.value();
  164. }
  165. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#get-all-navigables-whose-current-session-history-entry-will-change-or-reload
  166. Vector<JS::Handle<Navigable>> TraversableNavigable::get_all_navigables_whose_current_session_history_entry_will_change_or_reload(int target_step) const
  167. {
  168. // 1. Let results be an empty list.
  169. Vector<JS::Handle<Navigable>> results;
  170. // 2. Let navigablesToCheck be « traversable ».
  171. Vector<JS::Handle<Navigable>> navigables_to_check;
  172. navigables_to_check.append(const_cast<TraversableNavigable&>(*this));
  173. // 3. For each navigable of navigablesToCheck:
  174. while (!navigables_to_check.is_empty()) {
  175. auto navigable = navigables_to_check.take_first();
  176. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  177. auto target_entry = navigable->get_the_target_history_entry(target_step);
  178. // 2. If targetEntry is not navigable's current session history entry or targetEntry's document state's reload pending is true, then append navigable to results.
  179. if (target_entry != navigable->current_session_history_entry() || target_entry->document_state->reload_pending()) {
  180. results.append(*navigable);
  181. }
  182. // 3. If targetEntry's document is navigable's document, and targetEntry's document state's reload pending is false, then extend navigablesToCheck with the child navigables of navigable.
  183. if (target_entry->document_state->document() == navigable->active_document() && !target_entry->document_state->reload_pending()) {
  184. navigables_to_check.extend(navigable->child_navigables());
  185. }
  186. }
  187. // 4. Return results.
  188. return results;
  189. }
  190. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-navigables-that-only-need-history-object-length/index-update
  191. Vector<JS::Handle<Navigable>> TraversableNavigable::get_all_navigables_that_only_need_history_object_length_index_update(int target_step) const
  192. {
  193. // NOTE: Other navigables might not be impacted by the traversal. For example, if the response is a 204, the currently active document will remain.
  194. // Additionally, going 'back' after a 204 will change the current session history entry, but the active session history entry will already be correct.
  195. // 1. Let results be an empty list.
  196. Vector<JS::Handle<Navigable>> results;
  197. // 2. Let navigablesToCheck be « traversable ».
  198. Vector<JS::Handle<Navigable>> navigables_to_check;
  199. navigables_to_check.append(const_cast<TraversableNavigable&>(*this));
  200. // 3. For each navigable of navigablesToCheck:
  201. while (!navigables_to_check.is_empty()) {
  202. auto navigable = navigables_to_check.take_first();
  203. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  204. auto target_entry = navigable->get_the_target_history_entry(target_step);
  205. // 2. If targetEntry is navigable's current session history entry and targetEntry's document state's reload pending is false, then:
  206. if (target_entry == navigable->current_session_history_entry() && !target_entry->document_state->reload_pending()) {
  207. // 1. Append navigable to results.
  208. results.append(navigable);
  209. // 2. Extend navigablesToCheck with navigable's child navigables.
  210. navigables_to_check.extend(navigable->child_navigables());
  211. }
  212. }
  213. // 4. Return results.
  214. return results;
  215. }
  216. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-navigables-that-might-experience-a-cross-document-traversal
  217. Vector<JS::Handle<Navigable>> TraversableNavigable::get_all_navigables_that_might_experience_a_cross_document_traversal(int target_step) const
  218. {
  219. // NOTE: From traversable's session history traversal queue's perspective, these documents are candidates for going cross-document during the
  220. // traversal described by targetStep. They will not experience a cross-document traversal if the status code for their target document is
  221. // HTTP 204 No Content.
  222. // Note that if a given navigable might experience a cross-document traversal, this algorithm will return navigable but not its child navigables.
  223. // Those would end up unloaded, not traversed.
  224. // 1. Let results be an empty list.
  225. Vector<JS::Handle<Navigable>> results;
  226. // 2. Let navigablesToCheck be « traversable ».
  227. Vector<JS::Handle<Navigable>> navigables_to_check;
  228. navigables_to_check.append(const_cast<TraversableNavigable&>(*this));
  229. // 3. For each navigable of navigablesToCheck:
  230. while (!navigables_to_check.is_empty()) {
  231. auto navigable = navigables_to_check.take_first();
  232. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  233. auto target_entry = navigable->get_the_target_history_entry(target_step);
  234. // 2. If targetEntry's document is not navigable's document or targetEntry's document state's reload pending is true, then append navigable to results.
  235. // NOTE: Although navigable's active history entry can change synchronously, the new entry will always have the same Document,
  236. // so accessing navigable's document is reliable.
  237. if (target_entry->document_state->document() != navigable->active_document() || target_entry->document_state->reload_pending()) {
  238. results.append(navigable);
  239. }
  240. // 3. Otherwise, extend navigablesToCheck with navigable's child navigables.
  241. // Adding child navigables to navigablesToCheck means those navigables will also be checked by this loop.
  242. // Child navigables are only checked if the navigable's active document will not change as part of this traversal.
  243. else {
  244. navigables_to_check.extend(navigable->child_navigables());
  245. }
  246. }
  247. // 4. Return results.
  248. return results;
  249. }
  250. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#apply-the-history-step
  251. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_history_step(
  252. int step,
  253. bool check_for_cancelation,
  254. Optional<SourceSnapshotParams> source_snapshot_params,
  255. JS::GCPtr<Navigable> initiator_to_check,
  256. Optional<UserNavigationInvolvement> user_involvement_for_navigate_events)
  257. {
  258. auto& vm = this->vm();
  259. // FIXME: 1. Assert: This is running within traversable's session history traversal queue.
  260. // 2. Let targetStep be the result of getting the used step given traversable and step.
  261. auto target_step = get_the_used_step(step);
  262. // Note: Calling this early so we can re-use the same list in 3.2 and 6.
  263. auto change_or_reload_navigables = get_all_navigables_whose_current_session_history_entry_will_change_or_reload(target_step);
  264. // 3. If initiatorToCheck is not null, then:
  265. if (initiator_to_check != nullptr) {
  266. // 1. Assert: sourceSnapshotParams is not null.
  267. VERIFY(source_snapshot_params.has_value());
  268. // 2. For each navigable of get all navigables whose current session history entry will change or reload:
  269. // if initiatorToCheck is not allowed by sandboxing to navigate navigable given sourceSnapshotParams, then return "initiator-disallowed".
  270. for (auto const& navigable : change_or_reload_navigables) {
  271. if (!initiator_to_check->allowed_by_sandboxing_to_navigate(*navigable, *source_snapshot_params))
  272. return HistoryStepResult::InitiatorDisallowed;
  273. }
  274. }
  275. // 4. Let navigablesCrossingDocuments be the result of getting all navigables that might experience a cross-document traversal given traversable and targetStep.
  276. [[maybe_unused]] auto navigables_crossing_documents = get_all_navigables_that_might_experience_a_cross_document_traversal(target_step);
  277. // 5. FIXME: If checkForCancelation is true, and the result of checking if unloading is canceled given navigablesCrossingDocuments, traversable, targetStep,
  278. // and userInvolvementForNavigateEvents is not "continue", then return that result.
  279. (void)check_for_cancelation;
  280. // 6. Let changingNavigables be the result of get all navigables whose current session history entry will change or reload given traversable and targetStep.
  281. auto changing_navigables = move(change_or_reload_navigables);
  282. // 7. Let nonchangingNavigablesThatStillNeedUpdates be the result of getting all navigables that only need history object length/index update given traversable and targetStep.
  283. auto non_changing_navigables_that_still_need_updates = get_all_navigables_that_only_need_history_object_length_index_update(target_step);
  284. // 8. For each navigable of changingNavigables:
  285. for (auto& navigable : changing_navigables) {
  286. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  287. auto target_entry = navigable->get_the_target_history_entry(target_step);
  288. // 2. Set navigable's current session history entry to targetEntry.
  289. navigable->set_current_session_history_entry(target_entry);
  290. // 3. Set navigable's ongoing navigation to "traversal".
  291. navigable->set_ongoing_navigation(Traversal::Tag);
  292. }
  293. // 9. Let totalChangeJobs be the size of changingNavigables.
  294. auto total_change_jobs = changing_navigables.size();
  295. // 10. Let completedChangeJobs be 0.
  296. size_t completed_change_jobs = 0;
  297. struct ChangingNavigableContinuationState {
  298. JS::Handle<DOM::Document> displayed_document;
  299. JS::Handle<SessionHistoryEntry> target_entry;
  300. JS::Handle<Navigable> navigable;
  301. bool update_only = false;
  302. };
  303. // 11. Let changingNavigableContinuations be an empty queue of changing navigable continuation states.
  304. // NOTE: This queue is used to split the operations on changingNavigables into two parts. Specifically, changingNavigableContinuations holds data for the second part.
  305. Queue<ChangingNavigableContinuationState> changing_navigable_continuations;
  306. // 12. For each navigable of changingNavigables, queue a global task on the navigation and traversal task source of navigable's active window to run the steps:
  307. for (auto& navigable : changing_navigables) {
  308. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), [&] {
  309. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  310. if (navigable->has_been_destroyed())
  311. return;
  312. // 1. Let displayedEntry be navigable's active session history entry.
  313. auto displayed_entry = navigable->active_session_history_entry();
  314. // 2. Let targetEntry be navigable's current session history entry.
  315. auto target_entry = navigable->current_session_history_entry();
  316. // 3. Let changingNavigableContinuation be a changing navigable continuation state with:
  317. auto changing_navigable_continuation = ChangingNavigableContinuationState {
  318. .displayed_document = displayed_entry->document_state->document(),
  319. .target_entry = target_entry,
  320. .navigable = navigable,
  321. .update_only = false
  322. };
  323. // 4. If displayedEntry is targetEntry and targetEntry's document state's reload pending is false, then:
  324. if (displayed_entry == target_entry && !target_entry->document_state->reload_pending()) {
  325. // 1. Set changingNavigableContinuation's update-only to true.
  326. changing_navigable_continuation.update_only = true;
  327. // 2. Enqueue changingNavigableContinuation on changingNavigableContinuations.
  328. changing_navigable_continuations.enqueue(move(changing_navigable_continuation));
  329. // 3. Abort these steps.
  330. return;
  331. }
  332. // 5. Let oldOrigin be targetEntry's document state's origin.
  333. auto old_origin = target_entry->document_state->origin();
  334. auto after_document_populated = [old_origin, target_entry, changing_navigable_continuation, &changing_navigable_continuations, &vm, &navigable]() mutable {
  335. // 1. If targetEntry's document is null, then set changingNavigableContinuation's update-only to true.
  336. if (!target_entry->document_state->document()) {
  337. changing_navigable_continuation.update_only = true;
  338. }
  339. else {
  340. // 2. If targetEntry's document's origin is not oldOrigin, then set targetEntry's classic history API state to StructuredSerializeForStorage(null).
  341. if (target_entry->document_state->document()->origin() != old_origin) {
  342. target_entry->classic_history_api_state = MUST(structured_serialize_for_storage(vm, JS::js_null()));
  343. }
  344. // 3. If all of the following are true:
  345. // - navigable's parent is null;
  346. // - targetEntry's document's browsing context is not an auxiliary browsing context whose opener browsing context is non-null; and
  347. // - targetEntry's document's origin is not oldOrigin,
  348. // then set targetEntry's document state's navigable target name to the empty string.
  349. if (navigable->parent() != nullptr
  350. && target_entry->document_state->document()->browsing_context()->opener_browsing_context() == nullptr
  351. && target_entry->document_state->origin() != old_origin) {
  352. target_entry->document_state->set_navigable_target_name(String {});
  353. }
  354. }
  355. // 4. Enqueue changingNavigableContinuation on changingNavigableContinuations.
  356. changing_navigable_continuations.enqueue(move(changing_navigable_continuation));
  357. };
  358. // 6. If targetEntry's document is null, or targetEntry's document state's reload pending is true, then:
  359. if (!target_entry->document_state->document() || target_entry->document_state->reload_pending()) {
  360. // FIXME: 1. Let navTimingType be "back_forward" if targetEntry's document is null; otherwise "reload".
  361. // 2. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
  362. auto target_snapshot_params = navigable->snapshot_target_snapshot_params();
  363. // 3. Let potentiallyTargetSpecificSourceSnapshotParams be sourceSnapshotParams.
  364. Optional<SourceSnapshotParams> potentially_target_specific_source_snapshot_params = source_snapshot_params;
  365. // 4. If potentiallyTargetSpecificSourceSnapshotParams is null, then set it to the result of snapshotting source snapshot params given navigable's active document.
  366. if (!potentially_target_specific_source_snapshot_params.has_value()) {
  367. potentially_target_specific_source_snapshot_params = navigable->active_document()->snapshot_source_snapshot_params();
  368. }
  369. // 5. Set targetEntry's document state's reload pending to false.
  370. target_entry->document_state->set_reload_pending(false);
  371. // 6. Let allowPOST be targetEntry's document state's reload pending.
  372. auto allow_POST = target_entry->document_state->reload_pending();
  373. // 7. In parallel, attempt to populate the history entry's document for targetEntry, given navigable, potentiallyTargetSpecificSourceSnapshotParams,
  374. // targetSnapshotParams, with allowPOST set to allowPOST and completionSteps set to queue a global task on the navigation and traversal task source given
  375. // navigable's active window to run afterDocumentPopulated.
  376. Platform::EventLoopPlugin::the().deferred_invoke([target_entry, potentially_target_specific_source_snapshot_params, target_snapshot_params, this, allow_POST, navigable, after_document_populated] {
  377. navigable->populate_session_history_entry_document(target_entry, *potentially_target_specific_source_snapshot_params, target_snapshot_params, {}, Empty {}, CSPNavigationType::Other, allow_POST, [this, after_document_populated]() mutable {
  378. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [after_document_populated]() mutable {
  379. after_document_populated();
  380. });
  381. })
  382. .release_value_but_fixme_should_propagate_errors();
  383. });
  384. }
  385. // Otherwise, run afterDocumentPopulated immediately.
  386. else {
  387. after_document_populated();
  388. }
  389. });
  390. }
  391. // 13. Let navigablesThatMustWaitBeforeHandlingSyncNavigation be an empty set.
  392. Vector<JS::GCPtr<Navigable>> navigables_that_must_wait_before_handling_sync_navigation;
  393. // 14. While completedChangeJobs does not equal totalChangeJobs:
  394. while (completed_change_jobs != total_change_jobs) {
  395. // NOTE: Synchronous navigations that are intended to take place before this traversal jump the queue at this point,
  396. // so they can be added to the correct place in traversable's session history entries before this traversal
  397. // potentially unloads their document. More details can be found here (https://html.spec.whatwg.org/multipage/browsing-the-web.html#sync-navigation-steps-queue-jumping-examples)
  398. // 1. If traversable's running nested apply history step is false, then:
  399. if (!m_running_nested_apply_history_step) {
  400. // 1. While traversable's session history traversal queue's algorithm set contains one or more synchronous
  401. // navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation:
  402. // 1. Let steps be the first item in traversable's session history traversal queue's algorithm set
  403. // that is synchronous navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation.
  404. // 2. Remove steps from traversable's session history traversal queue's algorithm set.
  405. for (auto steps = m_session_history_traversal_queue.first_synchronous_navigation_steps_with_target_navigable_not_contained_in(navigables_that_must_wait_before_handling_sync_navigation);
  406. steps.target_navigable != nullptr;
  407. steps = m_session_history_traversal_queue.first_synchronous_navigation_steps_with_target_navigable_not_contained_in(navigables_that_must_wait_before_handling_sync_navigation)) {
  408. // 3. Set traversable's running nested apply history step to true.
  409. m_running_nested_apply_history_step = true;
  410. // 4. Run steps.
  411. steps.steps();
  412. // 5. Set traversable's running nested apply history step to false.
  413. m_running_nested_apply_history_step = false;
  414. }
  415. }
  416. // AD-HOC: Since currently populate_session_history_entry_document does not run in parallel
  417. // we call spin_until to interrupt execution of this function and let document population
  418. // to complete.
  419. Platform::EventLoopPlugin::the().spin_until([&] {
  420. return !changing_navigable_continuations.is_empty() || completed_change_jobs == total_change_jobs;
  421. });
  422. if (changing_navigable_continuations.is_empty()) {
  423. continue;
  424. }
  425. // 2. Let changingNavigableContinuation be the result of dequeuing from changingNavigableContinuations.
  426. auto changing_navigable_continuation = changing_navigable_continuations.dequeue();
  427. // 3. If changingNavigableContinuation is nothing, then continue.
  428. // 4. Let displayedDocument be changingNavigableContinuation's displayed document.
  429. auto displayed_document = changing_navigable_continuation.displayed_document;
  430. // 5. Let targetEntry be changingNavigableContinuation's target entry.
  431. auto target_entry = changing_navigable_continuation.target_entry;
  432. // 6. Let navigable be changingNavigableContinuation's navigable.
  433. auto navigable = changing_navigable_continuation.navigable;
  434. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  435. if (navigable->has_been_destroyed())
  436. continue;
  437. // 7. Set navigable's ongoing navigation to null.
  438. navigable->set_ongoing_navigation({});
  439. // 8. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
  440. auto history_object_length_and_index = get_the_history_object_length_and_index(target_step);
  441. auto script_history_length = history_object_length_and_index.script_history_length;
  442. auto script_history_index = history_object_length_and_index.script_history_index;
  443. // 9. Append navigable to navigablesThatMustWaitBeforeHandlingSyncNavigation.
  444. navigables_that_must_wait_before_handling_sync_navigation.append(*navigable);
  445. // 10. Let entriesForNavigationAPI be the result of getting session history entries for the navigation API given navigable and targetStep.
  446. auto entries_for_navigation_api = get_session_history_entries_for_the_navigation_api(*navigable, target_step);
  447. // 11. Queue a global task on the navigation and traversal task source given navigable's active window to run the steps:
  448. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), [&completed_change_jobs, target_entry, navigable, displayed_document, update_only = changing_navigable_continuation.update_only, script_history_length, script_history_index, entries_for_navigation_api = move(entries_for_navigation_api), user_involvement_for_navigate_events]() mutable {
  449. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  450. if (navigable->has_been_destroyed()) {
  451. return;
  452. }
  453. // 1. If changingNavigableContinuation's update-only is false, then:
  454. if (!update_only) {
  455. // 1. If targetEntry's document does not equal displayedDocument, then:
  456. if (target_entry->document_state->document().ptr() != displayed_document.ptr()) {
  457. // 1. Unload displayedDocument given targetEntry's document.
  458. displayed_document->unload(target_entry->document_state->document());
  459. // 2. For each childNavigable of displayedDocument's descendant navigables, queue a global task on the navigation and traversal task source given
  460. // childNavigable's active window to unload childNavigable's active document.
  461. for (auto child_navigable : displayed_document->descendant_navigables()) {
  462. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), [child_navigable] {
  463. child_navigable->active_document()->unload();
  464. });
  465. }
  466. }
  467. // 3. Activate history entry targetEntry for navigable.
  468. navigable->activate_history_entry(*target_entry);
  469. }
  470. // 2. If navigable is not traversable, and targetEntry is not navigable's current session history entry, and targetEntry's document state's origin is the same as
  471. // navigable's current session history entry's document state's origin, then fire a traverse navigate event given targetEntry and userInvolvementForNavigateEvents.
  472. auto target_origin = target_entry->document_state->origin();
  473. auto current_origin = navigable->current_session_history_entry()->document_state->origin();
  474. bool const is_same_origin = target_origin.has_value() && current_origin.has_value() && target_origin->is_same_origin(*current_origin);
  475. if (!navigable->is_traversable()
  476. && target_entry.ptr() != navigable->current_session_history_entry()
  477. && is_same_origin) {
  478. navigable->active_window()->navigation()->fire_a_traverse_navigate_event(*target_entry, user_involvement_for_navigate_events.value_or(UserNavigationInvolvement::None));
  479. }
  480. // 3. Let updateDocument be an algorithm step which performs update document for history step application given targetEntry's document,
  481. // targetEntry, changingNavigableContinuation's update-only, scriptHistoryLength, scriptHistoryIndex, and entriesForNavigationAPI.
  482. auto update_document = JS::SafeFunction<void()>([target_entry, update_only, script_history_length, script_history_index, entries_for_navigation_api = move(entries_for_navigation_api)] {
  483. target_entry->document_state->document()->update_for_history_step_application(*target_entry, update_only, script_history_length, script_history_index, entries_for_navigation_api);
  484. });
  485. // 4. If targetEntry's document is equal to displayedDocument, then perform updateDocument.
  486. if (target_entry->document_state->document() == displayed_document.ptr()) {
  487. update_document();
  488. }
  489. // 5. Otherwise, queue a global task on the navigation and traversal task source given targetEntry's document's relevant global object to perform updateDocument
  490. else {
  491. queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(*target_entry->document_state->document()), move(update_document));
  492. }
  493. // 6. Increment completedChangeJobs.
  494. completed_change_jobs++;
  495. });
  496. }
  497. // 15. Let totalNonchangingJobs be the size of nonchangingNavigablesThatStillNeedUpdates.
  498. auto total_non_changing_jobs = non_changing_navigables_that_still_need_updates.size();
  499. // 16. Let completedNonchangingJobs be 0.
  500. auto completed_non_changing_jobs = 0u;
  501. // 17. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
  502. auto length_and_index = get_the_history_object_length_and_index(target_step);
  503. auto script_history_length = length_and_index.script_history_length;
  504. auto script_history_index = length_and_index.script_history_index;
  505. // 18. For each navigable of nonchangingNavigablesThatStillNeedUpdates, queue a global task on the navigation and traversal task source given navigable's active window to run the steps:
  506. for (auto& navigable : non_changing_navigables_that_still_need_updates) {
  507. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), [&] {
  508. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  509. if (navigable->has_been_destroyed()) {
  510. ++completed_non_changing_jobs;
  511. return;
  512. }
  513. // 1. Let document be navigable's active document.
  514. auto document = navigable->active_document();
  515. // 2. Set document's history object's index to scriptHistoryIndex.
  516. document->history()->m_index = script_history_index;
  517. // 3. Set document's history object's length to scriptHistoryLength.
  518. document->history()->m_length = script_history_length;
  519. // 4. Increment completedNonchangingJobs.
  520. ++completed_non_changing_jobs;
  521. });
  522. }
  523. // 19. Wait for completedNonchangingJobs to equal totalNonchangingJobs.
  524. // AD-HOC: Since currently populate_session_history_entry_document does not run in parallel
  525. // we call spin_until to interrupt execution of this function and let document population
  526. // to complete.
  527. Platform::EventLoopPlugin::the().spin_until([&] {
  528. return completed_non_changing_jobs == total_non_changing_jobs;
  529. });
  530. // 20. Set traversable's current session history step to targetStep.
  531. m_current_session_history_step = target_step;
  532. // 21. Return "applied".
  533. return HistoryStepResult::Applied;
  534. }
  535. Vector<JS::NonnullGCPtr<SessionHistoryEntry>> TraversableNavigable::get_session_history_entries_for_the_navigation_api(JS::NonnullGCPtr<Navigable> navigable, int target_step)
  536. {
  537. // 1. Let rawEntries be the result of getting session history entries for navigable.
  538. auto raw_entries = navigable->get_session_history_entries();
  539. if (raw_entries.is_empty())
  540. return {};
  541. // 2. Let entriesForNavigationAPI be a new empty list.
  542. Vector<JS::NonnullGCPtr<SessionHistoryEntry>> entries_for_navigation_api;
  543. // 3. Let startingIndex be the index of the session history entry in rawEntries who has the greatest step less than or equal to targetStep.
  544. // FIXME: Use min/max_element algorithm or some such here
  545. int starting_index = 0;
  546. auto max_step = 0;
  547. for (auto i = 0u; i < raw_entries.size(); ++i) {
  548. auto const& entry = raw_entries[i];
  549. if (entry->step.has<int>()) {
  550. auto step = entry->step.get<int>();
  551. if (step <= target_step && step > max_step) {
  552. starting_index = static_cast<int>(i);
  553. }
  554. }
  555. }
  556. // 4. Append rawEntries[startingIndex] to entriesForNavigationAPI.
  557. entries_for_navigation_api.append(raw_entries[starting_index]);
  558. // 5. Let startingOrigin be rawEntries[startingIndex]'s document state's origin.
  559. auto starting_origin = raw_entries[starting_index]->document_state->origin();
  560. // 6. Let i be startingIndex − 1.
  561. auto i = starting_index - 1;
  562. // 7. While i > 0:
  563. while (i > 0) {
  564. auto& entry = raw_entries[static_cast<unsigned>(i)];
  565. // 1. If rawEntries[i]'s document state's origin is not same origin with startingOrigin, then break.
  566. auto entry_origin = entry->document_state->origin();
  567. if (starting_origin.has_value() && entry_origin.has_value() && !entry_origin->is_same_origin(*starting_origin))
  568. break;
  569. // 2. Prepend rawEntries[i] to entriesForNavigationAPI.
  570. entries_for_navigation_api.prepend(entry);
  571. // 3. Set i to i − 1.
  572. --i;
  573. }
  574. // 8. Set i to startingIndex + 1.
  575. i = starting_index + 1;
  576. // 9. While i < rawEntries's size:
  577. while (i < static_cast<int>(raw_entries.size())) {
  578. auto& entry = raw_entries[static_cast<unsigned>(i)];
  579. // 1. If rawEntries[i]'s document state's origin is not same origin with startingOrigin, then break.
  580. auto entry_origin = entry->document_state->origin();
  581. if (starting_origin.has_value() && entry_origin.has_value() && !entry_origin->is_same_origin(*starting_origin))
  582. break;
  583. // 2. Append rawEntries[i] to entriesForNavigationAPI.
  584. entries_for_navigation_api.append(entry);
  585. // 3. Set i to i + 1.
  586. ++i;
  587. }
  588. // 10. Return entriesForNavigationAPI.
  589. return entries_for_navigation_api;
  590. }
  591. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#clear-the-forward-session-history
  592. void TraversableNavigable::clear_the_forward_session_history()
  593. {
  594. // FIXME: 1. Assert: this is running within navigable's session history traversal queue.
  595. // 2. Let step be the navigable's current session history step.
  596. auto step = current_session_history_step();
  597. // 3. Let entryLists be the ordered set « navigable's session history entries ».
  598. Vector<Vector<JS::NonnullGCPtr<SessionHistoryEntry>>&> entry_lists;
  599. entry_lists.append(session_history_entries());
  600. // 4. For each entryList of entryLists:
  601. while (!entry_lists.is_empty()) {
  602. auto& entry_list = entry_lists.take_first();
  603. // 1. Remove every session history entry from entryList that has a step greater than step.
  604. entry_list.remove_all_matching([step](auto& entry) {
  605. return entry->step.template get<int>() > step;
  606. });
  607. // 2. For each entry of entryList:
  608. for (auto& entry : entry_list) {
  609. // 1. For each nestedHistory of entry's document state's nested histories, append nestedHistory's entries list to entryLists.
  610. for (auto& nested_history : entry->document_state->nested_histories()) {
  611. entry_lists.append(nested_history.entries);
  612. }
  613. }
  614. }
  615. }
  616. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#traverse-the-history-by-a-delta
  617. void TraversableNavigable::traverse_the_history_by_delta(int delta, Optional<DOM::Document&> source_document)
  618. {
  619. // 1. Let sourceSnapshotParams and initiatorToCheck be null.
  620. Optional<SourceSnapshotParams> source_snapshot_params = {};
  621. JS::GCPtr<Navigable> initiator_to_check = nullptr;
  622. // 2. Let userInvolvement be "browser UI".
  623. UserNavigationInvolvement user_involvement = UserNavigationInvolvement::BrowserUI;
  624. // 1. If sourceDocument is given, then:
  625. if (source_document.has_value()) {
  626. // 1. Set sourceSnapshotParams to the result of snapshotting source snapshot params given sourceDocument.
  627. source_snapshot_params = source_document->snapshot_source_snapshot_params();
  628. // 2. Set initiatorToCheck to sourceDocument's node navigable.
  629. initiator_to_check = source_document->navigable();
  630. // 3. Set userInvolvement to "none".
  631. user_involvement = UserNavigationInvolvement::None;
  632. }
  633. // 4. Append the following session history traversal steps to traversable:
  634. append_session_history_traversal_steps([this, delta, source_snapshot_params = move(source_snapshot_params), initiator_to_check, user_involvement] {
  635. // 1. Let allSteps be the result of getting all used history steps for traversable.
  636. auto all_steps = get_all_used_history_steps();
  637. // 2. Let currentStepIndex be the index of traversable's current session history step within allSteps.
  638. auto current_step_index = *all_steps.find_first_index(current_session_history_step());
  639. // 3. Let targetStepIndex be currentStepIndex plus delta
  640. auto target_step_index = current_step_index + delta;
  641. // 4. If allSteps[targetStepIndex] does not exist, then abort these steps.
  642. if (target_step_index >= all_steps.size()) {
  643. return;
  644. }
  645. // 5. Apply the traverse history step allSteps[targetStepIndex] to traversable, given sourceSnapshotParams,
  646. // initiatorToCheck, and userInvolvement.
  647. apply_the_traverse_history_step(all_steps[target_step_index], source_snapshot_params, initiator_to_check, user_involvement);
  648. });
  649. }
  650. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#update-for-navigable-creation/destruction
  651. TraversableNavigable::HistoryStepResult TraversableNavigable::update_for_navigable_creation_or_destruction()
  652. {
  653. // 1. Let step be traversable's current session history step.
  654. auto step = current_session_history_step();
  655. // 2. Return the result of applying the history step step to traversable given, false, null, null, and null.
  656. return apply_the_history_step(step, false, {}, {}, {});
  657. }
  658. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#apply-the-reload-history-step
  659. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_reload_history_step()
  660. {
  661. // 1. Let step be traversable's current session history step.
  662. auto step = current_session_history_step();
  663. // 2. Return the result of applying the history step step to traversable given true, null, null, and null.
  664. return apply_the_history_step(step, true, {}, {}, {});
  665. }
  666. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_push_or_replace_history_step(int step)
  667. {
  668. // 1. Return the result of applying the history step step to traversable given false, null, null, and null.
  669. return apply_the_history_step(step, false, {}, {}, {});
  670. }
  671. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_traverse_history_step(int step, Optional<SourceSnapshotParams> source_snapshot_params, JS::GCPtr<Navigable> initiator_to_check, UserNavigationInvolvement user_involvement)
  672. {
  673. // 1. Return the result of applying the history step step to traversable given true, sourceSnapshotParams, initiatorToCheck, and userInvolvement.
  674. return apply_the_history_step(step, true, move(source_snapshot_params), initiator_to_check, user_involvement);
  675. }
  676. // https://html.spec.whatwg.org/multipage/document-sequences.html#close-a-top-level-traversable
  677. void TraversableNavigable::close_top_level_traversable()
  678. {
  679. VERIFY(is_top_level_traversable());
  680. // 1. Let toUnload be traversable's active document's inclusive descendant navigables.
  681. auto to_unload = active_document()->inclusive_descendant_navigables();
  682. // FIXME: 2. If the result of checking if unloading is user-canceled for toUnload is true, then return.
  683. // 3. Unload the active documents of each of toUnload.
  684. for (auto navigable : to_unload) {
  685. navigable->active_document()->unload();
  686. }
  687. // 4. Destroy traversable.
  688. destroy_top_level_traversable();
  689. }
  690. // https://html.spec.whatwg.org/multipage/document-sequences.html#destroy-a-top-level-traversable
  691. void TraversableNavigable::destroy_top_level_traversable()
  692. {
  693. VERIFY(is_top_level_traversable());
  694. // 1. Let browsingContext be traversable's active browsing context.
  695. auto browsing_context = active_browsing_context();
  696. // 2. For each historyEntry in traversable's session history entries:
  697. for (auto& history_entry : m_session_history_entries) {
  698. // 1. Let document be historyEntry's document.
  699. auto document = history_entry->document_state->document();
  700. // 2. If document is not null, then destroy document.
  701. if (document)
  702. document->destroy();
  703. }
  704. // 3. Remove browsingContext.
  705. browsing_context->remove();
  706. // 4. Remove traversable from the user interface (e.g., close or hide its tab in a tabbed browser).
  707. page().client().page_did_close_top_level_traversable();
  708. // 5. Remove traversable from the user agent's top-level traversable set.
  709. user_agent_top_level_traversable_set().remove(this);
  710. }
  711. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#finalize-a-same-document-navigation
  712. void finalize_a_same_document_navigation(JS::NonnullGCPtr<TraversableNavigable> traversable, JS::NonnullGCPtr<Navigable> target_navigable, JS::NonnullGCPtr<SessionHistoryEntry> target_entry, JS::GCPtr<SessionHistoryEntry> entry_to_replace)
  713. {
  714. // NOTE: This is not in the spec but we should not navigate destroyed navigable.
  715. if (target_navigable->has_been_destroyed())
  716. return;
  717. // FIXME: 1. Assert: this is running on traversable's session history traversal queue.
  718. // 2. If targetNavigable's active session history entry is not targetEntry, then return.
  719. if (target_navigable->active_session_history_entry() != target_entry) {
  720. return;
  721. }
  722. // 3. Let targetStep be null.
  723. Optional<int> target_step;
  724. // 4. Let targetEntries be the result of getting session history entries for targetNavigable.
  725. auto& target_entries = target_navigable->get_session_history_entries();
  726. // 5. If entryToReplace is null, then:
  727. if (!entry_to_replace) {
  728. // 1. Clear the forward session history of traversable.
  729. traversable->clear_the_forward_session_history();
  730. // 2. Set targetStep to traversable's current session history step + 1.
  731. target_step = traversable->current_session_history_step() + 1;
  732. // 3. Set targetEntry's step to targetStep.
  733. target_entry->step = *target_step;
  734. // 4. Append targetEntry to targetEntries.
  735. target_entries.append(target_entry);
  736. } else {
  737. // 1. Replace entryToReplace with targetEntry in targetEntries.
  738. *(target_entries.find(*entry_to_replace)) = target_entry;
  739. // 2. Set targetEntry's step to entryToReplace's step.
  740. target_entry->step = entry_to_replace->step;
  741. // 3. Set targetStep to traversable's current session history step.
  742. target_step = traversable->current_session_history_step();
  743. }
  744. // 6. Apply the push/replace history step targetStep to traversable.
  745. traversable->apply_the_push_or_replace_history_step(*target_step);
  746. }
  747. // https://html.spec.whatwg.org/multipage/interaction.html#system-visibility-state
  748. void TraversableNavigable::set_system_visibility_state(VisibilityState visibility_state)
  749. {
  750. if (m_system_visibility_state == visibility_state)
  751. return;
  752. m_system_visibility_state = visibility_state;
  753. // When a user-agent determines that the system visibility state for
  754. // traversable navigable traversable has changed to newState, it must run the following steps:
  755. // 1. Let navigables be the inclusive descendant navigables of traversable's active document.
  756. auto navigables = active_document()->inclusive_descendant_navigables();
  757. // 2. For each navigable of navigables:
  758. for (auto& navigable : navigables) {
  759. // 1. Let document be navigable's active document.
  760. auto document = navigable->active_document();
  761. VERIFY(document);
  762. // 2. Queue a global task on the user interaction task source given document's relevant global object
  763. // to update the visibility state of document with newState.
  764. queue_global_task(Task::Source::UserInteraction, relevant_global_object(*document), [visibility_state, document] {
  765. document->update_the_visibility_state(visibility_state);
  766. });
  767. }
  768. }
  769. }