TraversableNavigable.cpp 53 KB

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