Navigable.cpp 73 KB

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