Navigable.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibWeb/Crypto/Crypto.h>
  8. #include <LibWeb/DOM/Document.h>
  9. #include <LibWeb/DOM/DocumentLoading.h>
  10. #include <LibWeb/Fetch/Fetching/Fetching.h>
  11. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  12. #include <LibWeb/Fetch/Infrastructure/FetchController.h>
  13. #include <LibWeb/Fetch/Infrastructure/URL.h>
  14. #include <LibWeb/HTML/BrowsingContext.h>
  15. #include <LibWeb/HTML/DocumentState.h>
  16. #include <LibWeb/HTML/HistoryHandlingBehavior.h>
  17. #include <LibWeb/HTML/Navigable.h>
  18. #include <LibWeb/HTML/Navigation.h>
  19. #include <LibWeb/HTML/NavigationParams.h>
  20. #include <LibWeb/HTML/POSTResource.h>
  21. #include <LibWeb/HTML/SandboxingFlagSet.h>
  22. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  23. #include <LibWeb/HTML/SessionHistoryEntry.h>
  24. #include <LibWeb/HTML/StructuredSerialize.h>
  25. #include <LibWeb/HTML/TraversableNavigable.h>
  26. #include <LibWeb/Infra/Strings.h>
  27. #include <LibWeb/Platform/EventLoopPlugin.h>
  28. #include <LibWeb/XHR/FormData.h>
  29. namespace Web::HTML {
  30. class ResponseHolder : public JS::Cell {
  31. JS_CELL(ResponseHolder, JS::Cell);
  32. public:
  33. [[nodiscard]] static JS::NonnullGCPtr<ResponseHolder> create(JS::VM& vm)
  34. {
  35. return vm.heap().allocate_without_realm<ResponseHolder>();
  36. }
  37. [[nodiscard]] JS::GCPtr<Fetch::Infrastructure::Response> response() const { return m_response; }
  38. void set_response(JS::GCPtr<Fetch::Infrastructure::Response> response) { m_response = response; }
  39. virtual void visit_edges(Cell::Visitor& visitor) override
  40. {
  41. visitor.visit(m_response);
  42. }
  43. private:
  44. JS::GCPtr<Fetch::Infrastructure::Response> m_response;
  45. };
  46. HashTable<Navigable*>& all_navigables()
  47. {
  48. static HashTable<Navigable*> set;
  49. return set;
  50. }
  51. // https://html.spec.whatwg.org/multipage/document-sequences.html#child-navigable
  52. Vector<JS::Handle<Navigable>> Navigable::child_navigables() const
  53. {
  54. Vector<JS::Handle<Navigable>> results;
  55. for (auto& entry : all_navigables()) {
  56. if (entry->current_session_history_entry()->step == SessionHistoryEntry::Pending::Tag)
  57. continue;
  58. if (entry->parent() == this)
  59. results.append(entry);
  60. }
  61. return results;
  62. }
  63. Navigable::Navigable()
  64. {
  65. all_navigables().set(this);
  66. }
  67. Navigable::~Navigable()
  68. {
  69. all_navigables().remove(this);
  70. }
  71. void Navigable::visit_edges(Cell::Visitor& visitor)
  72. {
  73. Base::visit_edges(visitor);
  74. visitor.visit(m_parent);
  75. visitor.visit(m_current_session_history_entry);
  76. visitor.visit(m_active_session_history_entry);
  77. visitor.visit(m_container);
  78. }
  79. void Navigable::set_delaying_load_events(bool value)
  80. {
  81. if (value) {
  82. auto document = container_document();
  83. VERIFY(document);
  84. m_delaying_the_load_event.emplace(*document);
  85. } else {
  86. m_delaying_the_load_event.clear();
  87. }
  88. }
  89. JS::GCPtr<Navigable> Navigable::navigable_with_active_document(JS::NonnullGCPtr<DOM::Document> document)
  90. {
  91. for (auto* navigable : all_navigables()) {
  92. if (navigable->active_document() == document)
  93. return navigable;
  94. }
  95. return nullptr;
  96. }
  97. // https://html.spec.whatwg.org/multipage/document-sequences.html#initialize-the-navigable
  98. ErrorOr<void> Navigable::initialize_navigable(JS::NonnullGCPtr<DocumentState> document_state, JS::GCPtr<Navigable> parent)
  99. {
  100. static int next_id = 0;
  101. m_id = TRY(String::number(next_id++));
  102. // 1. Let entry be a new session history entry, with
  103. JS::NonnullGCPtr<SessionHistoryEntry> entry = *heap().allocate_without_realm<SessionHistoryEntry>();
  104. // URL: document's URL
  105. entry->url = document_state->document()->url();
  106. // document state: documentState
  107. entry->document_state = document_state;
  108. // 2. Set navigable's current session history entry to entry.
  109. m_current_session_history_entry = entry;
  110. // 3. Set navigable's active session history entry to entry.
  111. m_active_session_history_entry = entry;
  112. // 4. Set navigable's parent to parent.
  113. m_parent = parent;
  114. return {};
  115. }
  116. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-target-history-entry
  117. JS::GCPtr<SessionHistoryEntry> Navigable::get_the_target_history_entry(int target_step) const
  118. {
  119. // 1. Let entries be the result of getting session history entries for navigable.
  120. auto& entries = get_session_history_entries();
  121. // 2. Return the item in entries that has the greatest step less than or equal to step.
  122. JS::GCPtr<SessionHistoryEntry> result = nullptr;
  123. for (auto& entry : entries) {
  124. auto entry_step = entry->step.get<int>();
  125. if (entry_step <= target_step) {
  126. if (!result || result->step.get<int>() < entry_step) {
  127. result = entry;
  128. }
  129. }
  130. }
  131. return result;
  132. }
  133. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#activate-history-entry
  134. void Navigable::activate_history_entry(JS::GCPtr<SessionHistoryEntry> entry)
  135. {
  136. // FIXME: 1. Save persisted state to the navigable's active session history entry.
  137. // 2. Let newDocument be entry's document.
  138. JS::GCPtr<DOM::Document> new_document = entry->document_state->document().ptr();
  139. // 3. Assert: newDocument's is initial about:blank is false, i.e., we never traverse
  140. // back to the initial about:blank Document because it always gets replaced when we
  141. // navigate away from it.
  142. VERIFY(!new_document->is_initial_about_blank());
  143. // 4. Set navigable's active session history entry to entry.
  144. m_active_session_history_entry = entry;
  145. // 5. Make active newDocument.
  146. new_document->make_active();
  147. // Not in the spec:
  148. if (is<TraversableNavigable>(*this) && parent() == nullptr) {
  149. if (auto* page = active_browsing_context()->page()) {
  150. page->client().page_did_start_loading(entry->url, false);
  151. }
  152. }
  153. }
  154. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-document
  155. JS::GCPtr<DOM::Document> Navigable::active_document()
  156. {
  157. // A navigable's active document is its active session history entry's document.
  158. return m_active_session_history_entry->document_state->document();
  159. }
  160. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-bc
  161. JS::GCPtr<BrowsingContext> Navigable::active_browsing_context()
  162. {
  163. // A navigable's active browsing context is its active document's browsing context.
  164. // If this navigable is a traversable navigable, then its active browsing context will be a top-level browsing context.
  165. if (auto document = active_document())
  166. return document->browsing_context();
  167. return nullptr;
  168. }
  169. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-wp
  170. JS::GCPtr<HTML::WindowProxy> Navigable::active_window_proxy()
  171. {
  172. // A navigable's active WindowProxy is its active browsing context's associated WindowProxy.
  173. if (auto browsing_context = active_browsing_context())
  174. return browsing_context->window_proxy();
  175. return nullptr;
  176. }
  177. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-window
  178. JS::GCPtr<HTML::Window> Navigable::active_window()
  179. {
  180. // A navigable's active window is its active WindowProxy's [[Window]].
  181. if (auto window_proxy = active_window_proxy())
  182. return window_proxy->window();
  183. return nullptr;
  184. }
  185. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-target
  186. String Navigable::target_name() const
  187. {
  188. // A navigable's target name is its active session history entry's document state's navigable target name.
  189. return active_session_history_entry()->document_state->navigable_target_name();
  190. }
  191. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-container
  192. JS::GCPtr<NavigableContainer> Navigable::container() const
  193. {
  194. // The container of a navigable navigable is the navigable container whose nested navigable is navigable, or null if there is no such element.
  195. return NavigableContainer::navigable_container_with_content_navigable(const_cast<Navigable&>(*this));
  196. }
  197. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-container-document
  198. JS::GCPtr<DOM::Document> Navigable::container_document() const
  199. {
  200. auto container = this->container();
  201. // 1. If navigable's container is null, then return null.
  202. if (!container)
  203. return nullptr;
  204. // 2. Return navigable's container's node document.
  205. return container->document();
  206. }
  207. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-traversable
  208. JS::GCPtr<TraversableNavigable> Navigable::traversable_navigable() const
  209. {
  210. // 1. Let navigable be inputNavigable.
  211. auto navigable = const_cast<Navigable*>(this);
  212. // 2. While navigable is not a traversable navigable, set navigable to navigable's parent.
  213. while (navigable && !is<TraversableNavigable>(*navigable))
  214. navigable = navigable->parent();
  215. // 3. Return navigable.
  216. return static_cast<TraversableNavigable*>(navigable);
  217. }
  218. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-top
  219. JS::GCPtr<TraversableNavigable> Navigable::top_level_traversable()
  220. {
  221. // 1. Let navigable be inputNavigable.
  222. auto navigable = this;
  223. // 2. While navigable's parent is not null, set navigable to navigable's parent.
  224. while (navigable->parent())
  225. navigable = navigable->parent();
  226. // 3. Return navigable.
  227. return verify_cast<TraversableNavigable>(navigable);
  228. }
  229. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#set-the-ongoing-navigation
  230. void Navigable::set_ongoing_navigation(Variant<Empty, Traversal, String> ongoing_navigation)
  231. {
  232. // 1. If navigable's ongoing navigation is equal to newValue, then return.
  233. if (m_ongoing_navigation == ongoing_navigation)
  234. return;
  235. // FIXME: 2. Inform the navigation API about aborting navigation given navigable.
  236. // 3. Set navigable's ongoing navigation to newValue.
  237. m_ongoing_navigation = ongoing_navigation;
  238. }
  239. Navigable::ChosenNavigable Navigable::choose_a_navigable(StringView name, TokenizedFeature::NoOpener, ActivateTab)
  240. {
  241. // 1. Let chosen be null.
  242. JS::GCPtr<Navigable> chosen = nullptr;
  243. // 2. Let windowType be "existing or none".
  244. auto window_type = WindowType::ExistingOrNone;
  245. // 3. Let sandboxingFlagSet be current's active document's active sandboxing flag set.
  246. [[maybe_unused]] auto sandboxing_flag_set = active_document()->active_sandboxing_flag_set();
  247. // 4. If name is the empty string or an ASCII case-insensitive match for "_self", then set chosen to currentNavigable.
  248. if (name.is_empty() || Infra::is_ascii_case_insensitive_match(name, "_self"sv)) {
  249. chosen = this;
  250. }
  251. // 5. Otherwise, if name is an ASCII case-insensitive match for "_parent",
  252. // set chosen to currentNavigable's parent, if any, and currentNavigable otherwise.
  253. else if (Infra::is_ascii_case_insensitive_match(name, "_parent"sv)) {
  254. if (auto parent = this->parent())
  255. chosen = parent;
  256. else
  257. chosen = this;
  258. }
  259. // 6. Otherwise, if name is an ASCII case-insensitive match for "_top",
  260. // set chosen to currentNavigable's traversable navigable.
  261. else if (Infra::is_ascii_case_insensitive_match(name, "_top"sv)) {
  262. chosen = traversable_navigable();
  263. }
  264. // 7. Otherwise, if name is not an ASCII case-insensitive match for "_blank",
  265. // there exists a navigable whose target name is the same as name, currentNavigable's
  266. // active browsing context is familiar with that navigable's active browsing context,
  267. // and the user agent determines that the two browsing contexts are related enough that
  268. // it is ok if they reach each other, set chosen to that navigable. If there are multiple
  269. // matching navigables, the user agent should pick one in some arbitrary consistent manner,
  270. // such as the most recently opened, most recently focused, or more closely related, and set
  271. // chosen to it.
  272. else if (!Infra::is_ascii_case_insensitive_match(name, "_blank"sv)) {
  273. TODO();
  274. }
  275. // Otherwise, a new top-level traversable is being requested, and what happens depends on the
  276. // user agent's configuration and abilities — it is determined by the rules given for the first
  277. // applicable option from the following list:
  278. else {
  279. TODO();
  280. }
  281. return { chosen.ptr(), window_type };
  282. }
  283. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-session-history-entries
  284. Vector<JS::NonnullGCPtr<SessionHistoryEntry>>& Navigable::get_session_history_entries() const
  285. {
  286. // 1. Let traversable be navigable's traversable navigable.
  287. auto traversable = traversable_navigable();
  288. // FIXME 2. Assert: this is running within traversable's session history traversal queue.
  289. // 3. If navigable is traversable, return traversable's session history entries.
  290. if (this == traversable)
  291. return traversable->session_history_entries();
  292. // 4. Let docStates be an empty ordered set of document states.
  293. Vector<JS::GCPtr<DocumentState>> doc_states;
  294. // 5. For each entry of traversable's session history entries, append entry's document state to docStates.
  295. for (auto& entry : traversable->session_history_entries())
  296. doc_states.append(entry->document_state);
  297. // 6. For each docState of docStates:
  298. while (!doc_states.is_empty()) {
  299. auto doc_state = doc_states.take_first();
  300. // 1. For each nestedHistory of docState's nested histories:
  301. for (auto& nested_history : doc_state->nested_histories()) {
  302. // 1. If nestedHistory's id equals navigable's id, return nestedHistory's entries.
  303. if (nested_history.id == id())
  304. return nested_history.entries;
  305. // 2. For each entry of nestedHistory's entries, append entry's document state to docStates.
  306. for (auto& entry : nested_history.entries)
  307. doc_states.append(entry->document_state);
  308. }
  309. }
  310. VERIFY_NOT_REACHED();
  311. }
  312. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-from-a-srcdoc-resource
  313. static WebIDL::ExceptionOr<NavigationParams> create_navigation_params_from_a_srcdoc_resource(JS::GCPtr<SessionHistoryEntry> entry, JS::GCPtr<Navigable> navigable, SourceSnapshotParams const&, Optional<String> navigation_id)
  314. {
  315. auto& vm = navigable->vm();
  316. auto& realm = navigable->active_window()->realm();
  317. // 1. Let documentResource be entry's document state's resource.
  318. auto document_resource = entry->document_state->resource();
  319. VERIFY(document_resource.has<String>());
  320. // 2. Let response be a new response with
  321. // URL: about:srcdoc
  322. // header list: (`Content-Type`, `text/html`)
  323. // body: the UTF-8 encoding of documentResource, as a body
  324. auto response = Fetch::Infrastructure::Response::create(vm);
  325. response->url_list().append(AK::URL("about:srcdoc"));
  326. auto header = TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html"sv));
  327. TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
  328. response->set_body(TRY(Fetch::Infrastructure::byte_sequence_as_body(realm, document_resource.get<String>().bytes())));
  329. // 3. Let responseOrigin be the result of determining the origin given response's URL, targetSnapshotParams's sandboxing flags, null, and entry's document state's origin.
  330. auto response_origin = determine_the_origin(*response->url(), SandboxingFlagSet {}, {}, entry->document_state->origin());
  331. // 4. Let coop be a new cross-origin opener policy.
  332. CrossOriginOpenerPolicy coop;
  333. // 5. Let coopEnforcementResult be a new cross-origin opener policy enforcement result with
  334. // url: response's URL
  335. // origin: responseOrigin
  336. // cross-origin opener policy: coop
  337. CrossOriginOpenerPolicyEnforcementResult coop_enforcement_result {
  338. .url = *response->url(),
  339. .origin = response_origin,
  340. .cross_origin_opener_policy = coop
  341. };
  342. // FIXME: 6. Let policyContainer be the result of determining navigation params policy container given response's URL, entry's document state's history policy container, null, navigable's container document's policy container, and null.
  343. // 7. Return a new navigation params, with
  344. // id: navigationId
  345. // request: null
  346. // response: response
  347. // origin: responseOrigin
  348. // FIXME: policy container: policyContainer
  349. // FIXME: final sandboxing flag set: targetSnapshotParams's sandboxing flags
  350. // cross-origin opener policy: coop
  351. // COOP enforcement result: coopEnforcementResult
  352. // reserved environment: null
  353. // navigable: navigable
  354. // FIXME: navigation timing type: navTimingType
  355. // fetch controller: null
  356. // commit early hints: null
  357. HTML::NavigationParams navigation_params {
  358. .id = navigation_id,
  359. .request = {},
  360. .response = *response,
  361. .origin = move(response_origin),
  362. .policy_container = PolicyContainer {},
  363. .final_sandboxing_flag_set = SandboxingFlagSet {},
  364. .cross_origin_opener_policy = move(coop),
  365. .coop_enforcement_result = move(coop_enforcement_result),
  366. .reserved_environment = {},
  367. .browsing_context = navigable->active_browsing_context(),
  368. .navigable = navigable,
  369. };
  370. return { navigation_params };
  371. }
  372. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-by-fetching
  373. static WebIDL::ExceptionOr<Optional<NavigationParams>> create_navigation_params_by_fetching(JS::GCPtr<SessionHistoryEntry> entry, JS::GCPtr<Navigable> navigable, SourceSnapshotParams const& source_snapshot_params, Optional<String> navigation_id)
  374. {
  375. auto& vm = navigable->vm();
  376. auto& realm = navigable->active_window()->realm();
  377. // FIXME: 1. Assert: this is running in parallel.
  378. // 2. Let documentResource be entry's document state's resource.
  379. auto document_resource = entry->document_state->resource();
  380. // 3. Let request be a new request, with
  381. // url: entry's URL
  382. // client: sourceSnapshotParams's fetch client
  383. // destination: "document"
  384. // credentials mode: "include"
  385. // use-URL-credentials flag: set
  386. // redirect mode: "manual"
  387. // replaces client id: navigable's active document's relevant settings object's id
  388. // mode: "navigate"
  389. // referrer: entry's document state's request referrer
  390. // FIXME: referrer policy: entry's document state's request referrer policy
  391. auto request = Fetch::Infrastructure::Request::create(vm);
  392. request->set_url(entry->url);
  393. request->set_client(source_snapshot_params.fetch_client);
  394. request->set_destination(Fetch::Infrastructure::Request::Destination::Document);
  395. request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::Include);
  396. request->set_use_url_credentials(true);
  397. request->set_redirect_mode(Fetch::Infrastructure::Request::RedirectMode::Manual);
  398. auto replaces_client_id = TRY_OR_THROW_OOM(vm, String::from_deprecated_string(navigable->active_document()->relevant_settings_object().id));
  399. request->set_replaces_client_id(replaces_client_id);
  400. request->set_mode(Fetch::Infrastructure::Request::Mode::Navigate);
  401. request->set_referrer(entry->document_state->request_referrer());
  402. // 4. If documentResource is a POST resource, then:
  403. if (document_resource.has<POSTResource>()) {
  404. // 1. Set request's method to `POST`.
  405. request->set_method(TRY_OR_THROW_OOM(vm, ByteBuffer::copy("post"sv.bytes())));
  406. // 2. Set request's body to documentResource's request body.
  407. request->set_body(document_resource.get<POSTResource>().request_body.value());
  408. // 3. Set `Content-Type` to documentResource's request content-type in request's header list.
  409. auto request_content_type = document_resource.get<POSTResource>().request_content_type;
  410. auto request_content_type_string = [request_content_type]() {
  411. switch (request_content_type) {
  412. case POSTResource::RequestContentType::ApplicationXWWWFormUrlencoded:
  413. return "application/x-www-form-urlencoded"sv;
  414. case POSTResource::RequestContentType::MultipartFormData:
  415. return "multipart/form-data"sv;
  416. case POSTResource::RequestContentType::TextPlain:
  417. return "text/plain"sv;
  418. default:
  419. VERIFY_NOT_REACHED();
  420. }
  421. }();
  422. auto header = TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, request_content_type_string));
  423. TRY_OR_THROW_OOM(vm, request->header_list()->append(move(header)));
  424. }
  425. // 5. If entry's document state's reload pending is true, then set request's reload-navigation flag.
  426. if (entry->document_state->reload_pending())
  427. request->set_reload_navigation(true);
  428. // 6. Otherwise, if entry's document state's ever populated is true, then set request's history-navigation flag.
  429. if (entry->document_state->ever_populated())
  430. request->set_history_navigation(true);
  431. // 9. Let response be null.
  432. // NOTE: We use a heap-allocated cell to hold the response pointer because the processResponse callback below
  433. // might use it after this stack is freed.
  434. auto response_holder = ResponseHolder::create(vm);
  435. // 10. Let responseOrigin be null.
  436. Optional<HTML::Origin> response_origin;
  437. // 11. Let fetchController be null.
  438. JS::GCPtr<Fetch::Infrastructure::FetchController> fetch_controller = nullptr;
  439. // 13. Let finalSandboxFlags be an empty sandboxing flag set.
  440. SandboxingFlagSet final_sandbox_flags = {};
  441. // 16. Let locationURL be null.
  442. ErrorOr<Optional<AK::URL>> location_url { OptionalNone {} };
  443. // 17. Let currentURL be request's current URL.
  444. AK::URL current_url = request->current_url();
  445. // FIXME: 18. Let commitEarlyHints be null.
  446. // 19. While true:
  447. while (true) {
  448. // FIXME: 1. If request's reserved client is not null and currentURL's origin is not the same as request's reserved client's creation URL's origin, then:
  449. // FIXME: 2. If request's reserved client is null, then:
  450. // FIXME: 3. If the result of should navigation request of type be blocked by Content Security Policy? given request and cspNavigationType is "Blocked", then set response to a network error and break. [CSP]
  451. // 4. Set response to null.
  452. response_holder->set_response(nullptr);
  453. // 5. If fetchController is null, then set fetchController to the result of fetching request,
  454. // with processEarlyHintsResponse set to processEarlyHintsResponseas defined below, processResponse
  455. // set to processResponse as defined below, and useParallelQueue set to true.
  456. if (!fetch_controller) {
  457. // FIXME: Let processEarlyHintsResponse be the following algorithm given a response earlyResponse:
  458. // Let processResponse be the following algorithm given a response fetchedResponse:
  459. auto process_response = [response_holder](JS::NonnullGCPtr<Fetch::Infrastructure::Response> fetch_response) {
  460. // 1. Set response to fetchedResponse.
  461. response_holder->set_response(fetch_response);
  462. };
  463. fetch_controller = TRY(Fetch::Fetching::fetch(
  464. realm,
  465. request,
  466. Fetch::Infrastructure::FetchAlgorithms::create(vm,
  467. {
  468. .process_request_body_chunk_length = {},
  469. .process_request_end_of_body = {},
  470. .process_early_hints_response = {},
  471. .process_response = move(process_response),
  472. .process_response_end_of_body = {},
  473. .process_response_consume_body = {},
  474. }),
  475. Fetch::Fetching::UseParallelQueue::Yes));
  476. }
  477. // 6. Otherwise, process the next manual redirect for fetchController.
  478. else {
  479. fetch_controller->process_next_manual_redirect();
  480. }
  481. // 7. Wait until either response is non-null, or navigable's ongoing navigation changes to no longer equal navigationId.
  482. Platform::EventLoopPlugin::the().spin_until([&]() {
  483. if (response_holder->response() != nullptr)
  484. return true;
  485. if (navigation_id.has_value() && (!navigable->ongoing_navigation().has<String>() || navigable->ongoing_navigation().get<String>() != *navigation_id))
  486. return true;
  487. return false;
  488. });
  489. // If the latter condition occurs, then abort fetchController, and return. Otherwise, proceed onward.
  490. if (navigation_id.has_value() && (!navigable->ongoing_navigation().has<String>() || navigable->ongoing_navigation().get<String>() != *navigation_id)) {
  491. fetch_controller->abort(realm, {});
  492. return OptionalNone {};
  493. }
  494. // 8. If request's body is null, then set entry's document state's resource to null.
  495. if (!request->body().has<Empty>()) {
  496. entry->document_state->set_resource(Empty {});
  497. }
  498. // 11. Set responseOrigin to the result of determining the origin given response's URL, finalSandboxFlags,
  499. // entry's document state's initiator origin, and null.
  500. response_origin = determine_the_origin(*response_holder->response()->url(), final_sandbox_flags, entry->document_state->initiator_origin(), {});
  501. // 14. Set locationURL to response's location URL given currentURL's fragment.
  502. auto location_url = response_holder->response()->location_url(current_url.fragment());
  503. VERIFY(!location_url.is_error());
  504. // 15. If locationURL is failure or null, then break.
  505. if (location_url.is_error() || !location_url.value().has_value()) {
  506. break;
  507. }
  508. // 16. Assert: locationURL is a URL.
  509. VERIFY(location_url.value()->is_valid());
  510. // FIXME: 17. Set entry's serialized state to StructuredSerializeForStorage(null).
  511. // 18. Let oldDocState be entry's document state.
  512. auto old_doc_state = entry->document_state;
  513. // 19. Set entry's document state to a new document state, with
  514. // history policy container: a clone of the oldDocState's history policy container if it is non-null; null otherwise
  515. // request referrer: oldDocState's request referrer
  516. // request referrer policy: oldDocState's request referrer policy
  517. // origin: oldDocState's origin
  518. // resource: oldDocState's resource
  519. // ever populated: oldDocState's ever populated
  520. // navigable target name: oldDocState's navigable target name
  521. entry->document_state = navigable->heap().allocate_without_realm<DocumentState>();
  522. entry->document_state->set_history_policy_container(old_doc_state->history_policy_container());
  523. entry->document_state->set_request_referrer(old_doc_state->request_referrer());
  524. entry->document_state->set_request_referrer_policy(old_doc_state->request_referrer_policy());
  525. entry->document_state->set_origin(old_doc_state->origin());
  526. entry->document_state->set_resource(old_doc_state->resource());
  527. entry->document_state->set_ever_populated(old_doc_state->ever_populated());
  528. entry->document_state->set_navigable_target_name(old_doc_state->navigable_target_name());
  529. // 20. If locationURL's scheme is not an HTTP(S) scheme, then:
  530. if (!Fetch::Infrastructure::is_http_or_https_scheme(location_url.value()->scheme())) {
  531. // 1. Set entry's document state's resource to null.
  532. entry->document_state->set_resource(Empty {});
  533. // 2. Break.
  534. break;
  535. }
  536. // 21. Set currentURL to locationURL.
  537. current_url = location_url.value().value();
  538. // 22. Set entry's URL to currentURL.
  539. entry->url = current_url;
  540. }
  541. // FIXME: 20. If locationURL is a URL whose scheme is not a fetch scheme, then return a new non-fetch scheme navigation params, with
  542. // initiator origin request's current URL's origin
  543. if (!location_url.is_error() && location_url.value().has_value() && !Fetch::Infrastructure::is_fetch_scheme(location_url.value().value().scheme())) {
  544. TODO();
  545. }
  546. // 21. If any of the following are true:
  547. // - response is a network error;
  548. // - locationURL is failure; or
  549. // - locationURL is a URL whose scheme is a fetch scheme
  550. // then return null.
  551. if (response_holder->response()->is_network_error() || location_url.is_error() || (location_url.value().has_value() && Fetch::Infrastructure::is_fetch_scheme(location_url.value().value().scheme()))) {
  552. return OptionalNone {};
  553. }
  554. // 22. Assert: locationURL is null and response is not a network error.
  555. VERIFY(!location_url.value().has_value());
  556. VERIFY(!response_holder->response()->is_network_error());
  557. // FIXME: 23. Let resultPolicyContainer be the result of determining navigation params policy container given response's
  558. // URL, entry's document state's history policy container, sourceSnapshotParams's source policy container,
  559. // null, and responsePolicyContainer.
  560. // 25. Return a new navigation params, with
  561. // id: navigationId
  562. // request: request
  563. // response: response
  564. // origin: responseOrigin
  565. // FIXME: policy container: resultPolicyContainer
  566. // FIXME: final sandboxing flag set: finalSandboxFlags
  567. // FIXME: cross-origin opener policy: responseCOOP
  568. // FIXME: COOP enforcement result: coopEnforcementResult
  569. // FIXME: reserved environment: request's reserved client
  570. // navigable: navigable
  571. // FIXME: navigation timing type: navTimingType
  572. // fetch controller: fetchController
  573. // FIXME: commit early hints: commitEarlyHints
  574. HTML::NavigationParams navigation_params {
  575. .id = navigation_id,
  576. .request = request,
  577. .response = *response_holder->response(),
  578. .origin = *response_origin,
  579. .policy_container = PolicyContainer {},
  580. .final_sandboxing_flag_set = SandboxingFlagSet {},
  581. .cross_origin_opener_policy = CrossOriginOpenerPolicy {},
  582. .coop_enforcement_result = CrossOriginOpenerPolicyEnforcementResult {},
  583. .reserved_environment = {},
  584. .browsing_context = navigable->active_browsing_context(),
  585. .navigable = navigable,
  586. .fetch_controller = fetch_controller,
  587. };
  588. return { navigation_params };
  589. }
  590. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#attempt-to-populate-the-history-entry's-document
  591. WebIDL::ExceptionOr<void> Navigable::populate_session_history_entry_document(JS::GCPtr<SessionHistoryEntry> entry, Optional<NavigationParams> navigation_params, Optional<String> navigation_id, SourceSnapshotParams const& source_snapshot_params, bool allow_POST, Function<void()> completion_steps)
  592. {
  593. // FIXME: 1. Assert: this is running in parallel.
  594. // 2. Assert: if navigationParams is non-null, then navigationParams's response is non-null.
  595. if (navigation_params.has_value())
  596. VERIFY(navigation_params->response);
  597. // 3. Let currentBrowsingContext be navigable's active browsing context.
  598. [[maybe_unused]] auto current_browsing_context = active_browsing_context();
  599. // 4. Let documentResource be entry's document state's resource.
  600. auto document_resource = entry->document_state->resource();
  601. // 5. If navigationParams is null, then:
  602. if (!navigation_params.has_value()) {
  603. // 1. If documentResource is a string, then set navigationParams to the result
  604. // of creating navigation params from a srcdoc resource given entry, navigable,
  605. // targetSnapshotParams, navigationId, and navTimingType.
  606. if (document_resource.has<String>()) {
  607. navigation_params = create_navigation_params_from_a_srcdoc_resource(entry, this, source_snapshot_params, navigation_id).release_value_but_fixme_should_propagate_errors();
  608. }
  609. // 2. Otherwise, if both of the following are true:
  610. // - entry's URL's scheme is a fetch scheme; and
  611. // - documentResource is null, or allowPOST is true and documentResource's request body is not failure (FIXME: check if request body is not failure)
  612. else if (Fetch::Infrastructure::is_fetch_scheme(entry->url.scheme()) && (document_resource.has<Empty>() || allow_POST)) {
  613. navigation_params = create_navigation_params_by_fetching(entry, this, source_snapshot_params, navigation_id).release_value_but_fixme_should_propagate_errors();
  614. }
  615. // FIXME: 3. Otherwise, if entry's URL's scheme is not a fetch scheme, then set navigationParams to a new non-fetch scheme navigation params, with
  616. // initiator origin: entry's document state's initiator origin
  617. else {
  618. TODO();
  619. }
  620. }
  621. // NOTE: Not in the spec but queuing task on the next step will fail because active_window() does not exist for destroyed navigable.
  622. if (has_been_destroyed())
  623. return {};
  624. // 6. Queue a global task on the navigation and traversal task source, given navigable's active window, to run these steps:
  625. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this, entry, navigation_params, navigation_id, completion_steps = move(completion_steps)] {
  626. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  627. if (has_been_destroyed())
  628. return;
  629. // 1. If navigable's ongoing navigation no longer equals navigationId, then run completionSteps and return.
  630. if (navigation_id.has_value() && (!ongoing_navigation().has<String>() || ongoing_navigation().get<String>() != *navigation_id)) {
  631. completion_steps();
  632. return;
  633. }
  634. // 2. Let failure be false.
  635. auto failure = false;
  636. // FIXME: 3. If navigationParams is a non-fetch scheme navigation params, then set entry's document state's document to the result of running attempt to create a non-fetch
  637. // scheme document given entry's URL, navigable, targetSnapshotParams's sandboxing flags, navigationId, navTimingType, sourceSnapshotParams's has transient
  638. // activation, and navigationParams's initiator origin.
  639. // 4. Otherwise, if navigationParams is null, then set failure to true.
  640. if (!navigation_params.has_value()) {
  641. failure = true;
  642. }
  643. // FIXME: 5. Otherwise, if the result of should navigation response to navigation request of type in target be blocked by Content Security Policy? given navigationParams's request,
  644. // navigationParams's response, navigationParams's policy container's CSP list, cspNavigationType, and navigable is "Blocked", then set failure to true.
  645. // FIXME: 6. Otherwise, if navigationParams's reserved environment is non-null and the result of checking a navigation response's adherence to its embedder policy given
  646. // navigationParams's response, navigable, and navigationParams's policy container's embedder policy is false, then set failure to true.
  647. // 8. If failure is true, then:
  648. if (failure) {
  649. // 1. Set entry's document state's document to the result of creating a document for inline content that doesn't have a DOM, given navigable, null, and navTimingType.
  650. // The inline content should indicate to the user the sort of error that occurred.
  651. // FIXME: Use SourceGenerator to produce error page from file:///res/html/error.html
  652. // and display actual error from fetch response.
  653. auto error_html = String::formatted("<h1>Failed to load {}</h1>"sv, entry->url).release_value_but_fixme_should_propagate_errors();
  654. entry->document_state->set_document(create_document_for_inline_content(this, navigation_id, error_html));
  655. // 2. Set entry's document state's document's salvageable to false.
  656. entry->document_state->document()->set_salvageable(false);
  657. // FIXME: 3. If navigationParams is not null, then:
  658. if (navigation_params.has_value()) {
  659. TODO();
  660. }
  661. }
  662. // FIXME: 9. Otherwise, if navigationParams's response's status is 204 or 205, then:
  663. else if (navigation_params->response->status() == 204 || navigation_params->response->status() == 205) {
  664. // 1. Run completionSteps.
  665. completion_steps();
  666. // 2. Return.
  667. return;
  668. }
  669. // FIXME: 10. Otherwise, if navigationParams's response has a `Content-Disposition`
  670. // header specifying the attachment disposition type, then:
  671. // 11. Otherwise:
  672. else {
  673. // 1. Let document be the result of loading a document given navigationParams, sourceSnapshotParams,
  674. // and entry's document state's initiator origin.
  675. auto document = load_document(navigation_params);
  676. // 2. If document is null, then run completionSteps and return.
  677. if (!document) {
  678. VERIFY_NOT_REACHED();
  679. completion_steps();
  680. return;
  681. }
  682. // 3. Set entry's document state's document to document.
  683. entry->document_state->set_document(document.ptr());
  684. // 4. Set entry's document state's origin to document's origin.
  685. entry->document_state->set_origin(document->origin());
  686. }
  687. // FIXME: 12. If entry's document state's request referrer is "client", then set it to request's referrer.
  688. // 13. If entry's document state's document is not null, then set entry's document state's ever populated to true.
  689. if (entry->document_state->document()) {
  690. entry->document_state->set_ever_populated(true);
  691. }
  692. // 14. Run completionSteps.
  693. completion_steps();
  694. });
  695. return {};
  696. }
  697. // To navigate a navigable navigable to a URL url using a Document sourceDocument,
  698. // with an optional POST resource, string, or null documentResource (default null),
  699. // an optional response-or-null response (default null), an optional boolean exceptionsEnabled (default false),
  700. // an optional NavigationHistoryBehavior historyHandling (default "auto"),
  701. // an optional serialized state-or-null navigationAPIState (default null),
  702. // an optional entry list or null formDataEntryList (default null),
  703. // an optional referrer policy referrerPolicy (default the empty string),
  704. // and an optional user navigation involvement userInvolvement (default "none"):
  705. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
  706. WebIDL::ExceptionOr<void> Navigable::navigate(
  707. AK::URL const& url,
  708. JS::NonnullGCPtr<DOM::Document> source_document,
  709. Variant<Empty, String, POSTResource> document_resource,
  710. JS::GCPtr<Fetch::Infrastructure::Response> response,
  711. bool exceptions_enabled,
  712. Bindings::NavigationHistoryBehavior history_handling,
  713. Optional<SerializationRecord> navigation_api_state,
  714. Optional<Vector<XHR::FormDataEntry>&> form_data_entry_list,
  715. ReferrerPolicy::ReferrerPolicy referrer_policy,
  716. UserNaviagationInvolvement user_involvement)
  717. {
  718. auto& active_document = *this->active_document();
  719. auto& realm = active_document.realm();
  720. auto& vm = this->vm();
  721. // 1. Let cspNavigationType be "form-submission" if formDataEntryList is non-null; otherwise "other".
  722. auto csp_navigation_type = form_data_entry_list.has_value() ? CSPNavigationType::FormSubmission : CSPNavigationType::Other;
  723. // 2. Let sourceSnapshotParams be the result of snapshotting source snapshot params given sourceDocument.
  724. auto source_snapshot_params = source_document->snapshot_source_snapshot_params();
  725. // 3. Let initiatorOriginSnapshot be sourceDocument's origin.
  726. auto initiator_origin_snapshot = source_document->origin();
  727. // 4. Let initiatorBaseURLSnapshot be sourceDocument's document base URL.
  728. auto initiator_base_url_snapshot = source_document->base_url();
  729. // 5. If sourceDocument's node navigable is not allowed by sandboxing to navigate navigable given and sourceSnapshotParams, then:
  730. if (!source_document->navigable()->allowed_by_sandboxing_to_navigate(*this, source_snapshot_params)) {
  731. // 1. If exceptionsEnabled is true, then throw a "SecurityError" DOMException.
  732. if (exceptions_enabled) {
  733. return WebIDL::SecurityError::create(realm, "Source document's node navigable is not allowed to navigate"_fly_string);
  734. }
  735. // 2 Return.
  736. return {};
  737. }
  738. // 6. Let navigationId be the result of generating a random UUID.
  739. String navigation_id = TRY_OR_THROW_OOM(vm, Crypto::generate_random_uuid());
  740. // FIXME: 7. If the surrounding agent is equal to navigable's active document's relevant agent, then continue these steps.
  741. // Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to continue these steps.
  742. // 8. If navigable's active document's unload counter is greater than 0,
  743. // then invoke WebDriver BiDi navigation failed with a WebDriver BiDi navigation status whose id is navigationId,
  744. // status is "canceled", and url is url, and return.
  745. if (active_document.unload_counter() > 0) {
  746. // FIXME: invoke WebDriver BiDi navigation failed with a WebDriver BiDi navigation status whose id is navigationId,
  747. // status is "canceled", and url is url
  748. return {};
  749. }
  750. // 9. If historyHandling is "auto", then:
  751. if (history_handling == Bindings::NavigationHistoryBehavior::Auto) {
  752. // FIXME: Fix spec typo targetNavigable --> navigable
  753. // 1. If url equals navigable's active document's URL,
  754. // and initiatorOriginSnapshot is same origin with targetNavigable's active document's origin,
  755. // then set historyHandling to "replace".
  756. if (url.equals(active_document.url(), AK::URL::ExcludeFragment::Yes) && initiator_origin_snapshot.is_same_origin(active_document.origin()))
  757. history_handling = Bindings::NavigationHistoryBehavior::Replace;
  758. // 2. Otherwise, set historyHandling to "push".
  759. else
  760. history_handling = Bindings::NavigationHistoryBehavior::Push;
  761. }
  762. // 10. If the navigation must be a replace given url and navigable's active document, then set historyHandling to "replace".
  763. if (navigation_must_be_a_replace(url, active_document))
  764. history_handling = Bindings::NavigationHistoryBehavior::Replace;
  765. // 11. If all of the following are true:
  766. // - documentResource is null;
  767. // - response is null;
  768. // - url equals navigable's active session history entry's URL with exclude fragments set to true; and
  769. // - url's fragment is non-null
  770. if (document_resource.has<Empty>()
  771. && !response
  772. && url.equals(active_session_history_entry()->url, AK::URL::ExcludeFragment::Yes)
  773. && url.fragment().has_value()) {
  774. // 1. Navigate to a fragment given navigable, url, historyHandling, and navigationId.
  775. TRY(navigate_to_a_fragment(url, to_history_handling_behavior(history_handling), navigation_id));
  776. // 2. Return.
  777. return {};
  778. }
  779. // 12. If navigable's parent is non-null, then set navigable's is delaying load events to true.
  780. if (parent() != nullptr)
  781. set_delaying_load_events(true);
  782. // 13. Let targetBrowsingContext be navigable's active browsing context.
  783. [[maybe_unused]] auto target_browsing_context = active_browsing_context();
  784. // 14. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
  785. [[maybe_unused]] auto target_snapshot_params = snapshot_target_snapshot_params();
  786. // 15. Invoke WebDriver BiDi navigation started with targetBrowsingContext, and a new WebDriver BiDi navigation status whose id is navigationId, url is url, and status is "pending".
  787. // 16. If navigable's ongoing navigation is "traversal", then:
  788. if (ongoing_navigation().has<Traversal>()) {
  789. // FIXME: 1. Invoke WebDriver BiDi navigation failed with targetBrowsingContext and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is url.
  790. // 2. Return.
  791. return {};
  792. }
  793. // 17. Set navigable's ongoing navigation to navigationId.
  794. set_ongoing_navigation(navigation_id);
  795. // 18. If url's scheme is "javascript", then:
  796. if (url.scheme() == "javascript"sv) {
  797. // 1. Queue a global task on the navigation and traversal task source given navigable's active window to navigate to a javascript: URL given navigable, url, historyHandling, initiatorOriginSnapshot, and cspNavigationType.
  798. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this, url, history_handling, initiator_origin_snapshot, csp_navigation_type, navigation_id] {
  799. (void)navigate_to_a_javascript_url(url, to_history_handling_behavior(history_handling), initiator_origin_snapshot, csp_navigation_type, navigation_id);
  800. });
  801. // 2. Return.
  802. return {};
  803. }
  804. // 19. If all of the following are true:
  805. // - userInvolvement is not "browser UI";
  806. // - navigable's active document's origin is same origin-domain with sourceDocument's origin;
  807. // - navigable's active document's is initial about:blank is false; and
  808. // - url's scheme is a fetch scheme
  809. // then:
  810. if (user_involvement != UserNaviagationInvolvement::BrowserUI && active_document.origin().is_same_origin_domain(source_document->origin()) && !active_document.is_initial_about_blank() && Fetch::Infrastructure::is_fetch_scheme(url.scheme())) {
  811. // 1. Let navigation be navigable's active window's navigation API.
  812. auto navigation = active_window()->navigation();
  813. // 2. Let entryListForFiring be formDataEntryList if documentResource is a POST resource; otherwise, null.
  814. auto entry_list_for_firing = [&]() -> Optional<Vector<XHR::FormDataEntry>&> {
  815. if (document_resource.has<POSTResource>())
  816. return form_data_entry_list;
  817. return {};
  818. }();
  819. // 3. Let navigationAPIStateForFiring be navigationAPIState if navigationAPIState is not null;
  820. // otherwise, StructuredSerializeForStorage(undefined).
  821. auto navigation_api_state_for_firing = navigation_api_state.value_or(MUST(structured_serialize_for_storage(vm, JS::js_undefined())));
  822. // FIXME: 4. Let continue be the result of firing a push/replace/reload navigate event at navigation
  823. // with navigationType set to historyHandling, isSameDocument set to false, userInvolvement set to userInvolvement,
  824. // formDataEntryList set to entryListForFiring, destinationURL set to url, and navigationAPIState set to navigationAPIStateForFiring.
  825. (void)navigation;
  826. (void)entry_list_for_firing;
  827. (void)navigation_api_state_for_firing;
  828. // FIXME: 5. If continue is false, then return.
  829. }
  830. if (is_top_level_traversable()) {
  831. if (auto* page = active_browsing_context()->page())
  832. page->client().page_did_start_loading(url, false);
  833. }
  834. // 20. In parallel, run these steps:
  835. Platform::EventLoopPlugin::the().deferred_invoke([this, source_snapshot_params = move(source_snapshot_params), document_resource, url, navigation_id, referrer_policy, initiator_origin_snapshot, response, history_handling, initiator_base_url_snapshot] {
  836. // NOTE: Not in the spec but subsequent steps will fail because destroyed navigable does not have active document.
  837. if (has_been_destroyed())
  838. return;
  839. // FIXME: 1. Let unloadPromptCanceled be the result of checking if unloading is user-canceled for navigable's active document's inclusive descendant navigables.
  840. // FIXME: 2. If unloadPromptCanceled is true, or navigable's ongoing navigation is no longer navigationId, then:
  841. if (!ongoing_navigation().has<String>() || ongoing_navigation().get<String>() != navigation_id) {
  842. // FIXME: 1. Invoke WebDriver BiDi navigation failed with targetBrowsingContext and a new WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is url.
  843. // 2. Abort these steps.
  844. return;
  845. }
  846. // 3. Queue a global task on the navigation and traversal task source given navigable's active window to abort navigable's active document.
  847. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this] {
  848. VERIFY(this->active_document());
  849. this->active_document()->abort();
  850. });
  851. // 4. Let documentState be a new document state with
  852. // request referrer policy: referrerPolicy
  853. // initiator origin: initiatorOriginSnapshot
  854. // resource: documentResource
  855. // navigable target name: navigable's target name
  856. JS::NonnullGCPtr<DocumentState> document_state = *heap().allocate_without_realm<DocumentState>();
  857. document_state->set_request_referrer_policy(referrer_policy);
  858. document_state->set_initiator_origin(initiator_origin_snapshot);
  859. document_state->set_resource(document_resource);
  860. document_state->set_navigable_target_name(target_name());
  861. // 5. If url matches about:blank or is about:srcdoc, then set documentState's origin to documentState's initiator origin.
  862. // FIXME: should this say "matches about:srcdoc"
  863. if (url_matches_about_blank(url) || url == "about:srcdoc"sv) {
  864. // 1. Set documentState's origin to initiatorOriginSnapshot.
  865. document_state->set_origin(document_state->initiator_origin());
  866. // 2. Set documentState's about base URL to initiatorBaseURLSnapshot.
  867. document_state->set_about_base_url(initiator_base_url_snapshot);
  868. }
  869. // 6. Let historyEntry be a new session history entry, with its URL set to url and its document state set to documentState.
  870. JS::NonnullGCPtr<SessionHistoryEntry> history_entry = *heap().allocate_without_realm<SessionHistoryEntry>();
  871. history_entry->url = url;
  872. history_entry->document_state = document_state;
  873. // 8. Let navigationParams be null.
  874. Optional<NavigationParams> navigation_params;
  875. // FIXME: 9. If response is non-null:
  876. if (response) {
  877. }
  878. // 10. Attempt to populate the history entry's document
  879. // for historyEntry, given navigable, "navigate", sourceSnapshotParams,
  880. // targetSnapshotParams, navigationId, navigationParams, cspNavigationType, with allowPOST
  881. // set to true and completionSteps set to the following step:
  882. populate_session_history_entry_document(history_entry, navigation_params, navigation_id, source_snapshot_params, true, [this, history_entry, history_handling, navigation_id] {
  883. traversable_navigable()->append_session_history_traversal_steps([this, history_entry, history_handling, navigation_id] {
  884. if (this->has_been_destroyed()) {
  885. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  886. return;
  887. }
  888. if (this->ongoing_navigation() != navigation_id) {
  889. // NOTE: This check is not in the spec but we should not continue navigation if ongoing navigation id has changed.
  890. return;
  891. }
  892. finalize_a_cross_document_navigation(*this, to_history_handling_behavior(history_handling), history_entry);
  893. });
  894. }).release_value_but_fixme_should_propagate_errors();
  895. });
  896. return {};
  897. }
  898. WebIDL::ExceptionOr<void> Navigable::navigate_to_a_fragment(AK::URL const& url, HistoryHandlingBehavior history_handling, String navigation_id)
  899. {
  900. (void)navigation_id;
  901. // FIXME: 1. Let navigation be navigable's active window's navigation API.
  902. // FIXME: 2. Let destinationNavigationAPIState be navigable's active session history entry's navigation API state.
  903. // FIXME: 3. If navigationAPIState is not null, then set destinationNavigationAPIState to navigationAPIState.
  904. // FIXME: 4. Let continue be the result of firing a push/replace/reload navigate event at navigation with navigationType set to historyHandling, isSameDocument set to true,
  905. // userInvolvement set to userInvolvement, and destinationURL set to url, and navigationAPIState set to destinationNavigationAPIState.
  906. // FIXME: 5. If continue is false, then return.
  907. // 6. Let historyEntry be a new session history entry, with
  908. // URL: url
  909. // document state: navigable's active session history entry's document state
  910. // navigation API state: destinationNavigationAPIState
  911. // scroll restoration mode: navigable's active session history entry's scroll restoration mode
  912. JS::NonnullGCPtr<SessionHistoryEntry> history_entry = heap().allocate_without_realm<SessionHistoryEntry>();
  913. history_entry->url = url;
  914. history_entry->document_state = active_session_history_entry()->document_state;
  915. history_entry->scroll_restoration_mode = active_session_history_entry()->scroll_restoration_mode;
  916. // 7. Let entryToReplace be navigable's active session history entry if historyHandling is "replace", otherwise null.
  917. auto entry_to_replace = history_handling == HistoryHandlingBehavior::Replace ? active_session_history_entry() : nullptr;
  918. // FIXME: 8. Let history be navigable's active document's history object.
  919. // FIXME: 9. Let scriptHistoryIndex be history's index.
  920. // FIXME: 10. Let scriptHistoryIndex be history's index.
  921. // 11. If historyHandling is "push", then:
  922. if (history_handling == HistoryHandlingBehavior::Push) {
  923. // FIXME: 1. Set history's state to null.
  924. // FIXME: 2. Increment scriptHistoryIndex.
  925. // FIXME: 3. Set scriptHistoryLength to scriptHistoryIndex + 1.
  926. }
  927. // 12. Set navigable's active session history entry to historyEntry.
  928. m_active_session_history_entry = history_entry;
  929. // FIXME: 13. Update document for history step application given navigable's active document, historyEntry, true, scriptHistoryIndex, and scriptHistoryLength.
  930. // FIXME: 14. Update the navigation API entries for a same-document navigation given navigation, historyEntry, and historyHandling.
  931. // 15. Scroll to the fragment given navigable's active document.
  932. // FIXME: Specification doesn't say when document url needs to update during fragment navigation
  933. active_document()->set_url(url);
  934. active_document()->scroll_to_the_fragment();
  935. // 16. Let traversable be navigable's traversable navigable.
  936. auto traversable = traversable_navigable();
  937. // 17. Append the following session history synchronous navigation steps involving navigable to traversable:
  938. traversable->append_session_history_traversal_steps([this, traversable, history_entry, entry_to_replace, navigation_id] {
  939. if (this->ongoing_navigation() != navigation_id) {
  940. // NOTE: This check is not in the spec but we should not continue navigation if ongoing navigation id has changed.
  941. return;
  942. }
  943. // 1. Finalize a same-document navigation given traversable, navigable, historyEntry, and entryToReplace.
  944. finalize_a_same_document_navigation(*traversable, *this, history_entry, entry_to_replace);
  945. // FIXME: 2. Invoke WebDriver BiDi fragment navigated with navigable's active browsing context and a new WebDriver BiDi
  946. // navigation status whose id is navigationId, url is url, and status is "complete".
  947. });
  948. return {};
  949. }
  950. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#evaluate-a-javascript:-url
  951. WebIDL::ExceptionOr<JS::GCPtr<DOM::Document>> Navigable::evaluate_javascript_url(AK::URL const& url, Origin const& new_document_origin, String navigation_id)
  952. {
  953. auto& vm = this->vm();
  954. auto& realm = active_window()->realm();
  955. // 1. Let urlString be the result of running the URL serializer on url.
  956. auto url_string = url.serialize();
  957. // 2. Let encodedScriptSource be the result of removing the leading "javascript:" from urlString.
  958. auto encoded_script_source = url_string.substring_view(11, url_string.length() - 11);
  959. // FIXME: 3. Let scriptSource be the UTF-8 decoding of the percent-decoding of encodedScriptSource.
  960. // 4. Let settings be targetNavigable's active document's relevant settings object.
  961. auto& settings = active_document()->relevant_settings_object();
  962. // 5. Let baseURL be settings's API base URL.
  963. auto base_url = settings.api_base_url();
  964. // 6. Let script be the result of creating a classic script given scriptSource, settings, baseURL, and the default classic script fetch options.
  965. auto script = HTML::ClassicScript::create("(javascript url)", encoded_script_source, settings, base_url);
  966. // 7. Let evaluationStatus be the result of running the classic script script.
  967. auto evaluation_status = script->run();
  968. // 8. Let result be null.
  969. String result;
  970. // 9. If evaluationStatus is a normal completion, and evaluationStatus.[[Value]] is a String, then set result to evaluationStatus.[[Value]].
  971. if (evaluation_status.type() == JS::Completion::Type::Normal && evaluation_status.value()->is_string()) {
  972. result = evaluation_status.value()->as_string().utf8_string();
  973. } else {
  974. // 10. Otherwise, return null.
  975. return nullptr;
  976. }
  977. // 11. Let response be a new response with
  978. // URL: targetNavigable's active document's URL
  979. // header list: «(`Content-Type`, `text/html;charset=utf-8`)»
  980. // body: the UTF-8 encoding of result, as a body
  981. auto response = Fetch::Infrastructure::Response::create(vm);
  982. response->url_list().append(active_document()->url());
  983. auto header = TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html"sv));
  984. TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
  985. response->set_body(TRY(Fetch::Infrastructure::byte_sequence_as_body(realm, result.bytes())));
  986. // 12. Let policyContainer be targetNavigable's active document's policy container.
  987. auto const& policy_container = active_document()->policy_container();
  988. // FIXME: 13. Let finalSandboxFlags be policyContainer's CSP list's CSP-derived sandboxing flags.
  989. // FIXME: 14. Let coop be targetNavigable's active document's cross-origin opener policy.
  990. auto const& coop = active_document()->cross_origin_opener_policy();
  991. // 15. Let coopEnforcementResult be a new cross-origin opener policy enforcement result with
  992. // url: url
  993. // origin: newDocumentOrigin
  994. // cross-origin opener policy: coop
  995. CrossOriginOpenerPolicyEnforcementResult coop_enforcement_result {
  996. .url = url,
  997. .origin = new_document_origin,
  998. .cross_origin_opener_policy = coop,
  999. };
  1000. // 16. Let navigationParams be a new navigation params, with
  1001. // id: navigationId
  1002. // navigable: targetNavigable
  1003. // request: null
  1004. // response: response
  1005. // fetch controller: null
  1006. // commit early hints: null
  1007. // COOP enforcement result: coopEnforcementResult
  1008. // reserved environment: null
  1009. // origin: newDocumentOrigin
  1010. // policy container: policyContainer
  1011. // final sandboxing flag set: finalSandboxFlags
  1012. // cross-origin opener policy: coop
  1013. // navigation timing type: "navigate"
  1014. // about base URL: targetNavigable's active document's about base URL
  1015. NavigationParams navigation_params {
  1016. .id = navigation_id,
  1017. .request = {},
  1018. .response = response,
  1019. .origin = new_document_origin,
  1020. .policy_container = policy_container,
  1021. .cross_origin_opener_policy = coop,
  1022. .coop_enforcement_result = move(coop_enforcement_result),
  1023. .reserved_environment = {},
  1024. .browsing_context = active_browsing_context(),
  1025. .navigable = this,
  1026. .fetch_controller = nullptr,
  1027. };
  1028. // 17. Return the result of loading an HTML document given navigationParams.
  1029. return load_document(navigation_params);
  1030. }
  1031. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate-to-a-javascript:-url
  1032. WebIDL::ExceptionOr<void> Navigable::navigate_to_a_javascript_url(AK::URL const& url, HistoryHandlingBehavior history_handling, Origin const& initiator_origin, CSPNavigationType csp_navigation_type, String navigation_id)
  1033. {
  1034. // 1. Assert: historyHandling is "replace".
  1035. VERIFY(history_handling == HistoryHandlingBehavior::Replace);
  1036. // 2. Set the ongoing navigation for targetNavigable to null.
  1037. set_ongoing_navigation({});
  1038. // 3. If initiatorOrigin is not same origin-domain with targetNavigable's active document's origin, then return.
  1039. if (!initiator_origin.is_same_origin_domain(active_document()->origin()))
  1040. return {};
  1041. // FIXME: 4. Let request be a new request whose URL is url.
  1042. // FIXME: 5. If the result of should navigation request of type be blocked by Content Security Policy? given request and cspNavigationType is "Blocked", then return.
  1043. (void)csp_navigation_type;
  1044. // 6. Let newDocument be the result of evaluating a javascript: URL given targetNavigable, url, and initiatorOrigin.
  1045. auto new_document = TRY(evaluate_javascript_url(url, initiator_origin, navigation_id));
  1046. // 7. If newDocument is null, then return.
  1047. if (!new_document) {
  1048. // NOTE: In this case, some JavaScript code was executed, but no new Document was created, so we will not perform a navigation.
  1049. return {};
  1050. }
  1051. // 8. Assert: initiatorOrigin is newDocument's origin.
  1052. VERIFY(initiator_origin == new_document->origin());
  1053. // 9. Let entryToReplace be targetNavigable's active session history entry.
  1054. auto entry_to_replace = active_session_history_entry();
  1055. // 10. Let oldDocState be entryToReplace's document state.
  1056. auto old_doc_state = entry_to_replace->document_state;
  1057. // 11. Let documentState be a new document state with
  1058. // document: newDocument
  1059. // history policy container: a clone of the oldDocState's history policy container if it is non-null; null otherwise
  1060. // request referrer: oldDocState's request referrer
  1061. // request referrer policy: oldDocState's request referrer policy
  1062. // initiator origin: initiatorOrigin
  1063. // origin: initiatorOrigin
  1064. // about base URL: oldDocState's about base URL
  1065. // resource: null
  1066. // ever populated: true
  1067. // navigable target name: oldDocState's navigable target name
  1068. JS::NonnullGCPtr<DocumentState> document_state = *heap().allocate_without_realm<DocumentState>();
  1069. document_state->set_document(new_document);
  1070. document_state->set_history_policy_container(old_doc_state->history_policy_container());
  1071. document_state->set_request_referrer(old_doc_state->request_referrer());
  1072. document_state->set_request_referrer_policy(old_doc_state->request_referrer_policy());
  1073. document_state->set_initiator_origin(initiator_origin);
  1074. document_state->set_origin(initiator_origin);
  1075. document_state->set_ever_populated(true);
  1076. document_state->set_navigable_target_name(old_doc_state->navigable_target_name());
  1077. // 12. Let historyEntry be a new session history entry, with
  1078. // URL: entryToReplace's URL
  1079. // document state: documentState
  1080. JS::NonnullGCPtr<SessionHistoryEntry> history_entry = *heap().allocate_without_realm<SessionHistoryEntry>();
  1081. history_entry->url = entry_to_replace->url;
  1082. history_entry->document_state = document_state;
  1083. // 13. Append session history traversal steps to targetNavigable's traversable to finalize a cross-document navigation with targetNavigable, historyHandling, and historyEntry.
  1084. traversable_navigable()->append_session_history_traversal_steps([this, history_entry, history_handling, navigation_id] {
  1085. if (this->ongoing_navigation() != navigation_id) {
  1086. // NOTE: This check is not in the spec but we should not continue navigation if ongoing navigation id has changed.
  1087. return;
  1088. }
  1089. finalize_a_cross_document_navigation(*this, history_handling, history_entry);
  1090. });
  1091. return {};
  1092. }
  1093. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#reload
  1094. void Navigable::reload()
  1095. {
  1096. // 1. Set navigable's active session history entry's document state's reload pending to true.
  1097. active_session_history_entry()->document_state->set_reload_pending(true);
  1098. // 2. Let traversable be navigable's traversable navigable.
  1099. auto traversable = traversable_navigable();
  1100. // 3. Append the following session history traversal steps to traversable:
  1101. traversable->append_session_history_traversal_steps([traversable] {
  1102. // 1. Apply the reload history step to traversable.
  1103. traversable->apply_the_reload_history_step();
  1104. });
  1105. }
  1106. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#the-navigation-must-be-a-replace
  1107. bool navigation_must_be_a_replace(AK::URL const& url, DOM::Document const& document)
  1108. {
  1109. return url.scheme() == "javascript"sv || document.is_initial_about_blank();
  1110. }
  1111. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#allowed-to-navigate
  1112. bool Navigable::allowed_by_sandboxing_to_navigate(Navigable const& target, SourceSnapshotParams const& source_snapshot_params)
  1113. {
  1114. auto& source = *this;
  1115. auto is_ancestor_of = [](Navigable const& a, Navigable const& b) {
  1116. for (auto parent = b.parent(); parent; parent = parent->parent()) {
  1117. if (parent.ptr() == &a)
  1118. return true;
  1119. }
  1120. return false;
  1121. };
  1122. // A navigable source is allowed by sandboxing to navigate a second navigable target,
  1123. // given a source snapshot params sourceSnapshotParams, if the following steps return true:
  1124. // 1. If source is target, then return true.
  1125. if (&source == &target)
  1126. return true;
  1127. // 2. If source is an ancestor of target, then return true.
  1128. if (is_ancestor_of(source, target))
  1129. return true;
  1130. // 3. If target is an ancestor of source, then:
  1131. if (is_ancestor_of(target, source)) {
  1132. // 1. If target is not a top-level traversable, then return true.
  1133. if (!target.is_top_level_traversable())
  1134. return true;
  1135. // 2. If sourceSnapshotParams's has transient activation is true, and sourceSnapshotParams's sandboxing flags's
  1136. // sandboxed top-level navigation with user activation browsing context flag is set, then return false.
  1137. if (source_snapshot_params.has_transient_activation && has_flag(source_snapshot_params.sandboxing_flags, SandboxingFlagSet::SandboxedTopLevelNavigationWithUserActivation))
  1138. return false;
  1139. // 3. If sourceSnapshotParams's has transient activation is false, and sourceSnapshotParams's sandboxing flags's
  1140. // sandboxed top-level navigation without user activation browsing context flag is set, then return false.
  1141. if (!source_snapshot_params.has_transient_activation && has_flag(source_snapshot_params.sandboxing_flags, SandboxingFlagSet::SandboxedTopLevelNavigationWithoutUserActivation))
  1142. return false;
  1143. // 4. Return true.
  1144. return true;
  1145. }
  1146. // 4. If target is a top-level traversable:
  1147. if (target.is_top_level_traversable()) {
  1148. // FIXME: 1. If source is the one permitted sandboxed navigator of target, then return true.
  1149. // 2. If sourceSnapshotParams's sandboxing flags's sandboxed navigation browsing context flag is set, then return false.
  1150. if (has_flag(source_snapshot_params.sandboxing_flags, SandboxingFlagSet::SandboxedNavigation))
  1151. return false;
  1152. // 3. Return true.
  1153. return true;
  1154. }
  1155. // 5. If sourceSnapshotParams's sandboxing flags's sandboxed navigation browsing context flag is set, then return false.
  1156. // 6. Return true.
  1157. return !has_flag(source_snapshot_params.sandboxing_flags, SandboxingFlagSet::SandboxedNavigation);
  1158. }
  1159. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#snapshotting-target-snapshot-params
  1160. TargetSnapshotParams Navigable::snapshot_target_snapshot_params()
  1161. {
  1162. // To snapshot target snapshot params given a navigable targetNavigable, return a new target snapshot params
  1163. // with sandboxing flags set to the result of determining the creation sandboxing flags given targetNavigable's
  1164. // active browsing context and targetNavigable's container.
  1165. return { determine_the_creation_sandboxing_flags(*active_browsing_context(), container()) };
  1166. }
  1167. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#finalize-a-cross-document-navigation
  1168. void finalize_a_cross_document_navigation(JS::NonnullGCPtr<Navigable> navigable, HistoryHandlingBehavior history_handling, JS::NonnullGCPtr<SessionHistoryEntry> history_entry)
  1169. {
  1170. // NOTE: This is not in the spec but we should not navigate destroyed navigable.
  1171. if (navigable->has_been_destroyed())
  1172. return;
  1173. // 1. FIXME: Assert: this is running on navigable's traversable navigable's session history traversal queue.
  1174. // 2. Set navigable's is delaying load events to false.
  1175. navigable->set_delaying_load_events(false);
  1176. // 3. If historyEntry's document is null, then return.
  1177. if (!history_entry->document_state->document())
  1178. return;
  1179. // 4. If all of the following are true:
  1180. // - navigable's parent is null;
  1181. // - historyEntry's document's browsing context is not an auxiliary browsing context whose opener browsing context is non-null; and
  1182. // - historyEntry's document's origin is not navigable's active document's origin
  1183. // then set historyEntry's document state's navigable target name to the empty string.
  1184. if (navigable->parent() == nullptr && history_entry->document_state->document()->browsing_context()->opener_browsing_context() != nullptr && history_entry->document_state->document()->origin() != navigable->active_document()->origin())
  1185. history_entry->document_state->set_navigable_target_name(String {});
  1186. // 5. Let entryToReplace be navigable's active session history entry if historyHandling is "replace", otherwise null.
  1187. auto entry_to_replace = history_handling == HistoryHandlingBehavior::Replace ? navigable->active_session_history_entry() : nullptr;
  1188. // 6. Let traversable be navigable's traversable navigable.
  1189. auto traversable = navigable->traversable_navigable();
  1190. // 7. Let targetStep be null.
  1191. int target_step;
  1192. // 8. Let targetEntries be the result of getting session history entries for navigable.
  1193. auto& target_entries = navigable->get_session_history_entries();
  1194. // 9. If entryToReplace is null, then:
  1195. if (entry_to_replace == nullptr) {
  1196. // 1. Clear the forward session history of traversable.
  1197. traversable->clear_the_forward_session_history();
  1198. // 2. Set targetStep to traversable's current session history step + 1.
  1199. target_step = traversable->current_session_history_step() + 1;
  1200. // 3. Set historyEntry's step to targetStep.
  1201. history_entry->step = target_step;
  1202. // 4. Append historyEntry to targetEntries.
  1203. target_entries.append(history_entry);
  1204. } else {
  1205. // 1. Replace entryToReplace with historyEntry in targetEntries.
  1206. *(target_entries.find(*entry_to_replace)) = history_entry;
  1207. // 2. Set historyEntry's step to entryToReplace's step.
  1208. history_entry->step = entry_to_replace->step;
  1209. // 3. If historyEntry's document state's origin is same origin with entryToReplace's document state's origin,
  1210. // then set historyEntry's navigation API key to entryToReplace's navigation API key.
  1211. if (history_entry->document_state->origin().has_value() && entry_to_replace->document_state->origin().has_value() && history_entry->document_state->origin()->is_same_origin(*entry_to_replace->document_state->origin())) {
  1212. history_entry->navigation_api_key = entry_to_replace->navigation_api_key;
  1213. }
  1214. // 4. Set targetStep to traversable's current session history step.
  1215. target_step = traversable->current_session_history_step();
  1216. }
  1217. // 10. Apply the push/replace history step targetStep to traversable.
  1218. traversable->apply_the_push_or_replace_history_step(target_step);
  1219. }
  1220. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#url-and-history-update-steps
  1221. void perform_url_and_history_update_steps(DOM::Document& document, AK::URL new_url, HistoryHandlingBehavior history_handling)
  1222. {
  1223. // 1. Let navigable be document's node navigable.
  1224. auto navigable = document.navigable();
  1225. // 2. Let activeEntry be navigable's active session history entry.
  1226. auto active_entry = navigable->active_session_history_entry();
  1227. // 3. Let newEntry be a new session history entry, with
  1228. // URL: newURL
  1229. // serialized state: if serializedData is not null, serializedData; otherwise activeEntry's classic history API state
  1230. // document state: activeEntry's document state
  1231. // scroll restoration mode: activeEntry's scroll restoration mode
  1232. // persisted user state: activeEntry's persisted user state
  1233. JS::NonnullGCPtr<SessionHistoryEntry> new_entry = document.heap().allocate_without_realm<SessionHistoryEntry>();
  1234. new_entry->url = new_url;
  1235. new_entry->document_state = active_entry->document_state;
  1236. new_entry->scroll_restoration_mode = active_entry->scroll_restoration_mode;
  1237. // 4. If document's is initial about:blank is true, then set historyHandling to "replace".
  1238. if (document.is_initial_about_blank()) {
  1239. history_handling = HistoryHandlingBehavior::Replace;
  1240. }
  1241. // 5. Let entryToReplace be activeEntry if historyHandling is "replace", otherwise null.
  1242. auto entry_to_replace = history_handling == HistoryHandlingBehavior::Replace ? active_entry : nullptr;
  1243. // 6. If historyHandling is "push", then:
  1244. if (history_handling == HistoryHandlingBehavior::Push) {
  1245. // FIXME: 1. Increment document's history object's index.
  1246. // FIXME: 2. Set document's history object's length to its index + 1.
  1247. TODO();
  1248. }
  1249. // FIXME: 7. If serializedData is not null, then restore the history object state given document and newEntry.
  1250. // 8. Set document's URL to newURL.
  1251. document.set_url(new_url);
  1252. // FIXME: 9. Set document's latest entry to newEntry.
  1253. // 10. Set navigable's active session history entry to newEntry.
  1254. navigable->set_active_session_history_entry(new_entry);
  1255. // FIXME: 11. Update the navigation API entries for a same-document navigation given document's relevant global object's navigation API, newEntry, and historyHandling.
  1256. // 12. Let traversable be navigable's traversable navigable.
  1257. auto traversable = navigable->traversable_navigable();
  1258. // 13. Append the following session history synchronous navigation steps involving navigable to traversable:
  1259. traversable->append_session_history_traversal_steps([traversable, navigable, new_entry, entry_to_replace] {
  1260. // 1. Finalize a same-document navigation given traversable, navigable, newEntry, and entryToReplace.
  1261. finalize_a_same_document_navigation(*traversable, *navigable, new_entry, entry_to_replace);
  1262. });
  1263. }
  1264. }