Navigable.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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/Navigable.h>
  17. #include <LibWeb/HTML/NavigationParams.h>
  18. #include <LibWeb/HTML/SessionHistoryEntry.h>
  19. #include <LibWeb/HTML/TraversableNavigable.h>
  20. #include <LibWeb/Infra/Strings.h>
  21. #include <LibWeb/Platform/EventLoopPlugin.h>
  22. namespace Web::HTML {
  23. class ResponseHolder : public JS::Cell {
  24. JS_CELL(ResponseHolder, JS::Cell);
  25. public:
  26. [[nodiscard]] static JS::NonnullGCPtr<ResponseHolder> create(JS::VM& vm)
  27. {
  28. return vm.heap().allocate_without_realm<ResponseHolder>();
  29. }
  30. [[nodiscard]] JS::GCPtr<Fetch::Infrastructure::Response> response() const { return m_response; }
  31. void set_response(JS::GCPtr<Fetch::Infrastructure::Response> response) { m_response = response; }
  32. virtual void visit_edges(Cell::Visitor& visitor) override
  33. {
  34. visitor.visit(m_response);
  35. }
  36. private:
  37. JS::GCPtr<Fetch::Infrastructure::Response> m_response;
  38. };
  39. static HashTable<Navigable*>& all_navigables()
  40. {
  41. static HashTable<Navigable*> set;
  42. return set;
  43. }
  44. // https://html.spec.whatwg.org/multipage/document-sequences.html#child-navigable
  45. Vector<JS::Handle<Navigable>> Navigable::child_navigables() const
  46. {
  47. Vector<JS::Handle<Navigable>> results;
  48. for (auto& entry : all_navigables()) {
  49. if (entry->parent() == this)
  50. results.append(entry);
  51. }
  52. return results;
  53. }
  54. Navigable::Navigable()
  55. {
  56. all_navigables().set(this);
  57. }
  58. Navigable::~Navigable()
  59. {
  60. all_navigables().remove(this);
  61. }
  62. void Navigable::visit_edges(Cell::Visitor& visitor)
  63. {
  64. Base::visit_edges(visitor);
  65. visitor.visit(m_parent);
  66. visitor.visit(m_current_session_history_entry);
  67. visitor.visit(m_active_session_history_entry);
  68. visitor.visit(m_container);
  69. }
  70. JS::GCPtr<Navigable> Navigable::navigable_with_active_document(JS::NonnullGCPtr<DOM::Document> document)
  71. {
  72. for (auto* navigable : all_navigables()) {
  73. if (navigable->active_document() == document)
  74. return navigable;
  75. }
  76. return nullptr;
  77. }
  78. // https://html.spec.whatwg.org/multipage/document-sequences.html#initialize-the-navigable
  79. ErrorOr<void> Navigable::initialize_navigable(JS::NonnullGCPtr<DocumentState> document_state, JS::GCPtr<Navigable> parent)
  80. {
  81. static int next_id = 0;
  82. m_id = TRY(String::number(next_id++));
  83. // 1. Let entry be a new session history entry, with
  84. JS::NonnullGCPtr<SessionHistoryEntry> entry = *heap().allocate_without_realm<SessionHistoryEntry>();
  85. // URL: document's URL
  86. entry->url = document_state->document()->url();
  87. // document state: documentState
  88. entry->document_state = document_state;
  89. // 2. Set navigable's current session history entry to entry.
  90. m_current_session_history_entry = entry;
  91. // 3. Set navigable's active session history entry to entry.
  92. m_active_session_history_entry = entry;
  93. // 4. Set navigable's parent to parent.
  94. m_parent = parent;
  95. return {};
  96. }
  97. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-target-history-entry
  98. JS::GCPtr<SessionHistoryEntry> Navigable::get_the_target_history_entry(int target_step) const
  99. {
  100. // 1. Let entries be the result of getting session history entries for navigable.
  101. auto& entries = get_session_history_entries();
  102. // 2. Return the item in entries that has the greatest step less than or equal to step.
  103. JS::GCPtr<SessionHistoryEntry> result = nullptr;
  104. for (auto& entry : entries) {
  105. auto entry_step = entry->step.get<int>();
  106. if (entry_step <= target_step) {
  107. if (!result || result->step.get<int>() < entry_step) {
  108. result = entry;
  109. }
  110. }
  111. }
  112. return result;
  113. }
  114. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#activate-history-entry
  115. void Navigable::activate_history_entry(JS::GCPtr<SessionHistoryEntry> entry)
  116. {
  117. // FIXME: 1. Save persisted state to the navigable's active session history entry.
  118. // 2. Let newDocument be entry's document.
  119. JS::GCPtr<DOM::Document> new_document = entry->document_state->document().ptr();
  120. // 3. Assert: newDocument's is initial about:blank is false, i.e., we never traverse
  121. // back to the initial about:blank Document because it always gets replaced when we
  122. // navigate away from it.
  123. VERIFY(!new_document->is_initial_about_blank());
  124. // 4. Set navigable's active session history entry to entry.
  125. m_active_session_history_entry = entry;
  126. // 5. Make active newDocument.
  127. new_document->make_active();
  128. // Not in the spec:
  129. if (is<TraversableNavigable>(*this) && parent() == nullptr) {
  130. if (auto* page = active_browsing_context()->page()) {
  131. page->client().page_did_start_loading(entry->url, false);
  132. }
  133. }
  134. }
  135. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-document
  136. JS::GCPtr<DOM::Document> Navigable::active_document()
  137. {
  138. // A navigable's active document is its active session history entry's document.
  139. return m_active_session_history_entry->document_state->document();
  140. }
  141. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-bc
  142. JS::GCPtr<BrowsingContext> Navigable::active_browsing_context()
  143. {
  144. // A navigable's active browsing context is its active document's browsing context.
  145. // If this navigable is a traversable navigable, then its active browsing context will be a top-level browsing context.
  146. if (auto document = active_document())
  147. return document->browsing_context();
  148. return nullptr;
  149. }
  150. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-wp
  151. JS::GCPtr<HTML::WindowProxy> Navigable::active_window_proxy()
  152. {
  153. // A navigable's active WindowProxy is its active browsing context's associated WindowProxy.
  154. if (auto browsing_context = active_browsing_context())
  155. return browsing_context->window_proxy();
  156. return nullptr;
  157. }
  158. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-window
  159. JS::GCPtr<HTML::Window> Navigable::active_window()
  160. {
  161. // A navigable's active window is its active WindowProxy's [[Window]].
  162. if (auto window_proxy = active_window_proxy())
  163. return window_proxy->window();
  164. return nullptr;
  165. }
  166. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-target
  167. String Navigable::target_name() const
  168. {
  169. // FIXME: A navigable's target name is its active session history entry's document state's navigable target name.
  170. dbgln("FIXME: Implement Navigable::target_name()");
  171. return {};
  172. }
  173. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-container
  174. JS::GCPtr<NavigableContainer> Navigable::container() const
  175. {
  176. // The container of a navigable navigable is the navigable container whose nested navigable is navigable, or null if there is no such element.
  177. return NavigableContainer::navigable_container_with_content_navigable(const_cast<Navigable&>(*this));
  178. }
  179. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-container-document
  180. JS::GCPtr<DOM::Document> Navigable::container_document() const
  181. {
  182. auto container = this->container();
  183. // 1. If navigable's container is null, then return null.
  184. if (!container)
  185. return nullptr;
  186. // 2. Return navigable's container's node document.
  187. return container->document();
  188. }
  189. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-traversable
  190. JS::GCPtr<TraversableNavigable> Navigable::traversable_navigable() const
  191. {
  192. // 1. Let navigable be inputNavigable.
  193. auto navigable = const_cast<Navigable*>(this);
  194. // 2. While navigable is not a traversable navigable, set navigable to navigable's parent.
  195. while (navigable && !is<TraversableNavigable>(*navigable))
  196. navigable = navigable->parent();
  197. // 3. Return navigable.
  198. return static_cast<TraversableNavigable*>(navigable);
  199. }
  200. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-top
  201. JS::GCPtr<TraversableNavigable> Navigable::top_level_traversable()
  202. {
  203. // 1. Let navigable be inputNavigable.
  204. auto navigable = this;
  205. // 2. While navigable's parent is not null, set navigable to navigable's parent.
  206. while (navigable->parent())
  207. navigable = navigable->parent();
  208. // 3. Return navigable.
  209. return verify_cast<TraversableNavigable>(navigable);
  210. }
  211. Navigable::ChosenNavigable Navigable::choose_a_navigable(StringView name, TokenizedFeature::NoOpener, ActivateTab)
  212. {
  213. // 1. Let chosen be null.
  214. JS::GCPtr<Navigable> chosen = nullptr;
  215. // 2. Let windowType be "existing or none".
  216. auto window_type = WindowType::ExistingOrNone;
  217. // 3. Let sandboxingFlagSet be current's active document's active sandboxing flag set.
  218. [[maybe_unused]] auto sandboxing_flag_set = active_document()->active_sandboxing_flag_set();
  219. // 4. If name is the empty string or an ASCII case-insensitive match for "_self", then set chosen to currentNavigable.
  220. if (name.is_empty() || Infra::is_ascii_case_insensitive_match(name, "_self"sv)) {
  221. chosen = this;
  222. }
  223. // 5. Otherwise, if name is an ASCII case-insensitive match for "_parent",
  224. // set chosen to currentNavigable's parent, if any, and currentNavigable otherwise.
  225. else if (Infra::is_ascii_case_insensitive_match(name, "_parent"sv)) {
  226. if (auto parent = this->parent())
  227. chosen = parent;
  228. else
  229. chosen = this;
  230. }
  231. // 6. Otherwise, if name is an ASCII case-insensitive match for "_top",
  232. // set chosen to currentNavigable's traversable navigable.
  233. else if (Infra::is_ascii_case_insensitive_match(name, "_top"sv)) {
  234. chosen = traversable_navigable();
  235. }
  236. // 7. Otherwise, if name is not an ASCII case-insensitive match for "_blank",
  237. // there exists a navigable whose target name is the same as name, currentNavigable's
  238. // active browsing context is familiar with that navigable's active browsing context,
  239. // and the user agent determines that the two browsing contexts are related enough that
  240. // it is ok if they reach each other, set chosen to that navigable. If there are multiple
  241. // matching navigables, the user agent should pick one in some arbitrary consistent manner,
  242. // such as the most recently opened, most recently focused, or more closely related, and set
  243. // chosen to it.
  244. else if (!Infra::is_ascii_case_insensitive_match(name, "_blank"sv)) {
  245. TODO();
  246. }
  247. // Otherwise, a new top-level traversable is being requested, and what happens depends on the
  248. // user agent's configuration and abilities — it is determined by the rules given for the first
  249. // applicable option from the following list:
  250. else {
  251. TODO();
  252. }
  253. return { chosen.ptr(), window_type };
  254. }
  255. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-session-history-entries
  256. Vector<JS::NonnullGCPtr<SessionHistoryEntry>>& Navigable::get_session_history_entries() const
  257. {
  258. // 1. Let traversable be navigable's traversable navigable.
  259. auto traversable = traversable_navigable();
  260. // FIXME 2. Assert: this is running within traversable's session history traversal queue.
  261. // 3. If navigable is traversable, return traversable's session history entries.
  262. if (this == traversable)
  263. return traversable->session_history_entries();
  264. // 4. Let docStates be an empty ordered set of document states.
  265. Vector<JS::GCPtr<DocumentState>> doc_states;
  266. // 5. For each entry of traversable's session history entries, append entry's document state to docStates.
  267. for (auto& entry : traversable->session_history_entries())
  268. doc_states.append(entry->document_state);
  269. // 6. For each docState of docStates:
  270. while (!doc_states.is_empty()) {
  271. auto doc_state = doc_states.take_first();
  272. // 1. For each nestedHistory of docState's nested histories:
  273. for (auto& nested_history : doc_state->nested_histories()) {
  274. // 1. If nestedHistory's id equals navigable's id, return nestedHistory's entries.
  275. if (nested_history.id == id())
  276. return nested_history.entries;
  277. // 2. For each entry of nestedHistory's entries, append entry's document state to docStates.
  278. for (auto& entry : nested_history.entries)
  279. doc_states.append(entry->document_state);
  280. }
  281. }
  282. VERIFY_NOT_REACHED();
  283. }
  284. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-from-a-srcdoc-resource
  285. 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)
  286. {
  287. auto& vm = navigable->vm();
  288. auto& realm = navigable->active_window()->realm();
  289. // 1. Let documentResource be entry's document state's resource.
  290. auto document_resource = entry->document_state->resource();
  291. VERIFY(document_resource.has<String>());
  292. // 2. Let response be a new response with
  293. // URL: about:srcdoc
  294. // header list: (`Content-Type`, `text/html`)
  295. // body: the UTF-8 encoding of documentResource, as a body
  296. auto response = Fetch::Infrastructure::Response::create(vm);
  297. response->url_list().append(AK::URL("about:srcdoc"));
  298. auto header = TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html"sv));
  299. TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
  300. response->set_body(TRY(Fetch::Infrastructure::byte_sequence_as_body(realm, document_resource.get<String>().bytes())));
  301. // 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.
  302. // 4. Let coop be a new cross-origin opener policy.
  303. CrossOriginOpenerPolicy coop;
  304. // 5. Let coopEnforcementResult be a new cross-origin opener policy enforcement result with
  305. // url: response's URL
  306. // FIXME: origin: responseOrigin
  307. // cross-origin opener policy: coop
  308. CrossOriginOpenerPolicyEnforcementResult coop_enforcement_result {
  309. .url = *response->url(),
  310. .origin = Origin {},
  311. .cross_origin_opener_policy = coop
  312. };
  313. // 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.
  314. // 7. Return a new navigation params, with
  315. // id: navigationId
  316. // request: null
  317. // response: response
  318. // FIXME: origin: responseOrigin
  319. // FIXME: policy container: policyContainer
  320. // FIXME: final sandboxing flag set: targetSnapshotParams's sandboxing flags
  321. // cross-origin opener policy: coop
  322. // COOP enforcement result: coopEnforcementResult
  323. // reserved environment: null
  324. // navigable: navigable
  325. // FIXME: navigation timing type: navTimingType
  326. // fetch controller: null
  327. // commit early hints: null
  328. HTML::NavigationParams navigation_params {
  329. .id = navigation_id,
  330. .request = {},
  331. .response = *response,
  332. .origin = Origin {},
  333. .policy_container = PolicyContainer {},
  334. .final_sandboxing_flag_set = SandboxingFlagSet {},
  335. .cross_origin_opener_policy = move(coop),
  336. .coop_enforcement_result = move(coop_enforcement_result),
  337. .reserved_environment = {},
  338. .browsing_context = navigable->active_browsing_context(),
  339. .navigable = navigable,
  340. };
  341. return { navigation_params };
  342. }
  343. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-by-fetching
  344. 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)
  345. {
  346. auto& vm = navigable->vm();
  347. auto& realm = navigable->active_window()->realm();
  348. // FIXME: 1. Assert: this is running in parallel.
  349. // 2. Let documentResource be entry's document state's resource.
  350. auto document_resource = entry->document_state->resource();
  351. // 3. Let request be a new request, with
  352. // url: entry's URL
  353. // client: sourceSnapshotParams's fetch client
  354. // destination: "document"
  355. // credentials mode: "include"
  356. // use-URL-credentials flag: set
  357. // redirect mode: "manual"
  358. // replaces client id: navigable's active document's relevant settings object's id
  359. // mode: "navigate"
  360. // referrer: entry's document state's request referrer
  361. // FIXME: referrer policy: entry's document state's request referrer policy
  362. auto request = Fetch::Infrastructure::Request::create(vm);
  363. request->set_url(entry->url);
  364. request->set_client(source_snapshot_params.fetch_client);
  365. request->set_destination(Fetch::Infrastructure::Request::Destination::Document);
  366. request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::Include);
  367. request->set_use_url_credentials(true);
  368. request->set_redirect_mode(Fetch::Infrastructure::Request::RedirectMode::Manual);
  369. auto replaces_client_id = TRY_OR_THROW_OOM(vm, String::from_deprecated_string(navigable->active_document()->relevant_settings_object().id));
  370. request->set_replaces_client_id(replaces_client_id);
  371. request->set_mode(Fetch::Infrastructure::Request::Mode::Navigate);
  372. request->set_referrer(entry->document_state->request_referrer());
  373. // 4. If documentResource is a POST resource, then:
  374. if (document_resource.has<POSTResource>()) {
  375. // 1. Set request's method to `POST`.
  376. request->set_method(TRY_OR_THROW_OOM(vm, ByteBuffer::copy("post"sv.bytes())));
  377. // 2. Set request's body to documentResource's request body.
  378. request->set_body(document_resource.get<POSTResource>().request_body.value());
  379. // 3. Set `Content-Type` to documentResource's request content-type in request's header list.
  380. auto request_content_type = document_resource.get<POSTResource>().request_content_type;
  381. auto request_content_type_string = [request_content_type]() {
  382. switch (request_content_type) {
  383. case POSTResource::RequestContentType::ApplicationXWWWFormUrlencoded:
  384. return "application/x-www-form-urlencoded"sv;
  385. case POSTResource::RequestContentType::MultipartFormData:
  386. return "multipart/form-data"sv;
  387. case POSTResource::RequestContentType::TextPlain:
  388. return "text/plain"sv;
  389. default:
  390. VERIFY_NOT_REACHED();
  391. }
  392. }();
  393. auto header = TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, request_content_type_string));
  394. TRY_OR_THROW_OOM(vm, request->header_list()->append(move(header)));
  395. }
  396. // 5. If entry's document state's reload pending is true, then set request's reload-navigation flag.
  397. if (entry->document_state->reload_pending())
  398. request->set_reload_navigation(true);
  399. // 6. Otherwise, if entry's document state's ever populated is true, then set request's history-navigation flag.
  400. if (entry->document_state->ever_populated())
  401. request->set_history_navigation(true);
  402. // 9. Let response be null.
  403. // NOTE: We use a heap-allocated cell to hold the response pointer because the processResponse callback below
  404. // might use it after this stack is freed.
  405. auto response_holder = ResponseHolder::create(vm);
  406. // 10. Let responseOrigin be null.
  407. Optional<HTML::Origin> response_origin;
  408. // 11. Let fetchController be null.
  409. JS::GCPtr<Fetch::Infrastructure::FetchController> fetch_controller = nullptr;
  410. // 13. Let finalSandboxFlags be an empty sandboxing flag set.
  411. SandboxingFlagSet final_sandbox_flags = {};
  412. // 16. Let locationURL be null.
  413. ErrorOr<Optional<AK::URL>> location_url { OptionalNone {} };
  414. // 17. Let currentURL be request's current URL.
  415. AK::URL current_url = request->current_url();
  416. // FIXME: 18. Let commitEarlyHints be null.
  417. // 19. While true:
  418. while (true) {
  419. // 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:
  420. // FIXME: 2. If request's reserved client is null, then:
  421. // 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]
  422. // 4. Set response to null.
  423. response_holder->set_response(nullptr);
  424. // 5. If fetchController is null, then set fetchController to the result of fetching request,
  425. // with processEarlyHintsResponse set to processEarlyHintsResponseas defined below, processResponse
  426. // set to processResponse as defined below, and useParallelQueue set to true.
  427. if (!fetch_controller) {
  428. // FIXME: Let processEarlyHintsResponse be the following algorithm given a response earlyResponse:
  429. // Let processResponse be the following algorithm given a response fetchedResponse:
  430. auto process_response = [response_holder](JS::NonnullGCPtr<Fetch::Infrastructure::Response> fetch_response) {
  431. // 1. Set response to fetchedResponse.
  432. response_holder->set_response(fetch_response);
  433. };
  434. fetch_controller = TRY(Fetch::Fetching::fetch(
  435. realm,
  436. request,
  437. Fetch::Infrastructure::FetchAlgorithms::create(vm,
  438. {
  439. .process_request_body_chunk_length = {},
  440. .process_request_end_of_body = {},
  441. .process_early_hints_response = {},
  442. .process_response = move(process_response),
  443. .process_response_end_of_body = {},
  444. .process_response_consume_body = {},
  445. }),
  446. Fetch::Fetching::UseParallelQueue::Yes));
  447. }
  448. // 6. Otherwise, process the next manual redirect for fetchController.
  449. else {
  450. fetch_controller->process_next_manual_redirect();
  451. }
  452. // 7. Wait until either response is non-null, or navigable's ongoing navigation changes to no longer equal navigationId.
  453. Platform::EventLoopPlugin::the().spin_until([&]() {
  454. if (response_holder->response() != nullptr)
  455. return true;
  456. if (navigation_id.has_value() && (!navigable->ongoing_navigation().has<String>() || navigable->ongoing_navigation().get<String>() != *navigation_id))
  457. return true;
  458. return false;
  459. });
  460. // If the latter condition occurs, then abort fetchController, and return. Otherwise, proceed onward.
  461. if (navigation_id.has_value() && (!navigable->ongoing_navigation().has<String>() || navigable->ongoing_navigation().get<String>() != *navigation_id)) {
  462. fetch_controller->abort(realm, {});
  463. return OptionalNone {};
  464. }
  465. // 8. If request's body is null, then set entry's document state's resource to null.
  466. if (!request->body().has<Empty>()) {
  467. entry->document_state->set_resource(Empty {});
  468. }
  469. // 11. Set responseOrigin to the result of determining the origin given response's URL, finalSandboxFlags,
  470. // entry's document state's initiator origin, and null.
  471. response_origin = determine_the_origin(*response_holder->response()->url(), final_sandbox_flags, entry->document_state->initiator_origin(), {});
  472. // 14. Set locationURL to response's location URL given currentURL's fragment.
  473. auto location_url = response_holder->response()->location_url(current_url.fragment());
  474. VERIFY(!location_url.is_error());
  475. // 15. If locationURL is failure or null, then break.
  476. if (location_url.is_error() || !location_url.value().has_value()) {
  477. break;
  478. }
  479. // 16. Assert: locationURL is a URL.
  480. VERIFY(location_url.value()->is_valid());
  481. // FIXME: 17. Set entry's serialized state to StructuredSerializeForStorage(null).
  482. // 18. Let oldDocState be entry's document state.
  483. auto old_doc_state = entry->document_state;
  484. // 19. Set entry's document state to a new document state, with
  485. // history policy container: a clone of the oldDocState's history policy container if it is non-null; null otherwise
  486. // request referrer: oldDocState's request referrer
  487. // request referrer policy: oldDocState's request referrer policy
  488. // origin: oldDocState's origin
  489. // resource: oldDocState's resource
  490. // ever populated: oldDocState's ever populated
  491. // navigable target name: oldDocState's navigable target name
  492. entry->document_state = navigable->heap().allocate_without_realm<DocumentState>();
  493. entry->document_state->set_history_policy_container(old_doc_state->history_policy_container());
  494. entry->document_state->set_request_referrer(old_doc_state->request_referrer());
  495. entry->document_state->set_request_referrer_policy(old_doc_state->request_referrer_policy());
  496. entry->document_state->set_origin(old_doc_state->origin());
  497. entry->document_state->set_resource(old_doc_state->resource());
  498. entry->document_state->set_ever_populated(old_doc_state->ever_populated());
  499. entry->document_state->set_navigable_target_name(old_doc_state->navigable_target_name());
  500. // 20. If locationURL's scheme is not an HTTP(S) scheme, then:
  501. if (!Fetch::Infrastructure::is_http_or_https_scheme(location_url.value()->scheme())) {
  502. // 1. Set entry's document state's resource to null.
  503. entry->document_state->set_resource(Empty {});
  504. // 2. Break.
  505. break;
  506. }
  507. // 21. Set currentURL to locationURL.
  508. current_url = location_url.value().value();
  509. // 22. Set entry's URL to currentURL.
  510. entry->url = current_url;
  511. }
  512. // FIXME: 20. If locationURL is a URL whose scheme is not a fetch scheme, then return a new non-fetch scheme navigation params, with
  513. // initiator origin request's current URL's origin
  514. if (!location_url.is_error() && location_url.value().has_value() && !Fetch::Infrastructure::is_fetch_scheme(location_url.value().value().scheme())) {
  515. TODO();
  516. }
  517. // 21. If any of the following are true:
  518. // - response is a network error;
  519. // - locationURL is failure; or
  520. // - locationURL is a URL whose scheme is a fetch scheme
  521. // then return null.
  522. 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()))) {
  523. return OptionalNone {};
  524. }
  525. // 22. Assert: locationURL is null and response is not a network error.
  526. VERIFY(!location_url.value().has_value());
  527. VERIFY(!response_holder->response()->is_network_error());
  528. // FIXME: 23. Let resultPolicyContainer be the result of determining navigation params policy container given response's
  529. // URL, entry's document state's history policy container, sourceSnapshotParams's source policy container,
  530. // null, and responsePolicyContainer.
  531. // 25. Return a new navigation params, with
  532. // id: navigationId
  533. // request: request
  534. // response: response
  535. // origin: responseOrigin
  536. // FIXME: policy container: resultPolicyContainer
  537. // FIXME: final sandboxing flag set: finalSandboxFlags
  538. // FIXME: cross-origin opener policy: responseCOOP
  539. // FIXME: COOP enforcement result: coopEnforcementResult
  540. // FIXME: reserved environment: request's reserved client
  541. // navigable: navigable
  542. // FIXME: navigation timing type: navTimingType
  543. // fetch controller: fetchController
  544. // FIXME: commit early hints: commitEarlyHints
  545. HTML::NavigationParams navigation_params {
  546. .id = navigation_id,
  547. .request = request,
  548. .response = *response_holder->response(),
  549. .origin = *response_origin,
  550. .policy_container = PolicyContainer {},
  551. .final_sandboxing_flag_set = SandboxingFlagSet {},
  552. .cross_origin_opener_policy = CrossOriginOpenerPolicy {},
  553. .coop_enforcement_result = CrossOriginOpenerPolicyEnforcementResult {},
  554. .reserved_environment = {},
  555. .browsing_context = navigable->active_browsing_context(),
  556. .navigable = navigable,
  557. .fetch_controller = fetch_controller,
  558. };
  559. return { navigation_params };
  560. }
  561. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#attempt-to-populate-the-history-entry's-document
  562. 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)
  563. {
  564. // FIXME: 1. Assert: this is running in parallel.
  565. // 2. Assert: if navigationParams is non-null, then navigationParams's response is non-null.
  566. if (navigation_params.has_value())
  567. VERIFY(navigation_params->response);
  568. // 3. Let currentBrowsingContext be navigable's active browsing context.
  569. [[maybe_unused]] auto current_browsing_context = active_browsing_context();
  570. // 4. Let documentResource be entry's document state's resource.
  571. auto document_resource = entry->document_state->resource();
  572. // 5. If navigationParams is null, then:
  573. if (!navigation_params.has_value()) {
  574. // 1. If documentResource is a string, then set navigationParams to the result
  575. // of creating navigation params from a srcdoc resource given entry, navigable,
  576. // targetSnapshotParams, navigationId, and navTimingType.
  577. if (document_resource.has<String>()) {
  578. navigation_params = create_navigation_params_from_a_srcdoc_resource(entry, this, source_snapshot_params, navigation_id).release_value_but_fixme_should_propagate_errors();
  579. }
  580. // 2. Otherwise, if both of the following are true:
  581. // - entry's URL's scheme is a fetch scheme; and
  582. // - documentResource is null, or allowPOST is true and documentResource's request body is not failure (FIXME: check if request body is not failure)
  583. else if (Fetch::Infrastructure::is_fetch_scheme(entry->url.scheme()) && (document_resource.has<Empty>() || allow_POST)) {
  584. navigation_params = create_navigation_params_by_fetching(entry, this, source_snapshot_params, navigation_id).release_value_but_fixme_should_propagate_errors();
  585. }
  586. // 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
  587. // initiator origin: entry's document state's initiator origin
  588. else {
  589. TODO();
  590. }
  591. }
  592. // 6. Queue a global task on the navigation and traversal task source, given navigable's active window, to run these steps:
  593. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this, entry, navigation_params, navigation_id, completion_steps = move(completion_steps)] {
  594. // 1. If navigable's ongoing navigation no longer equals navigationId, then run completionSteps and return.
  595. if (navigation_id.has_value() && (!ongoing_navigation().has<String>() || ongoing_navigation().get<String>() != *navigation_id)) {
  596. completion_steps();
  597. return;
  598. }
  599. // 2. Let failure be false.
  600. auto failure = false;
  601. // 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
  602. // scheme document given entry's URL, navigable, targetSnapshotParams's sandboxing flags, navigationId, navTimingType, sourceSnapshotParams's has transient
  603. // activation, and navigationParams's initiator origin.
  604. // 4. Otherwise, if navigationParams is null, then set failure to true.
  605. if (!navigation_params.has_value()) {
  606. failure = true;
  607. }
  608. // 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,
  609. // navigationParams's response, navigationParams's policy container's CSP list, cspNavigationType, and navigable is "Blocked", then set failure to true.
  610. // 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
  611. // navigationParams's response, navigable, and navigationParams's policy container's embedder policy is false, then set failure to true.
  612. // 8. If failure is true, then:
  613. if (failure) {
  614. // 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.
  615. // The inline content should indicate to the user the sort of error that occurred.
  616. // FIXME: Use SourceGenerator to produce error page from file:///res/html/error.html
  617. // and display actual error from fetch response.
  618. auto error_html = String::formatted("<h1>Failed to load {}</h1>"sv, entry->url).release_value_but_fixme_should_propagate_errors();
  619. entry->document_state->set_document(create_document_for_inline_content(this, navigation_id, error_html));
  620. // 2. Set entry's document state's document's salvageable to false.
  621. entry->document_state->document()->set_salvageable(false);
  622. // FIXME: 3. If navigationParams is not null, then:
  623. if (navigation_params.has_value()) {
  624. TODO();
  625. }
  626. }
  627. // FIXME: 9. Otherwise, if navigationParams's response's status is 204 or 205, then:
  628. else if (navigation_params->response->status() == 204 || navigation_params->response->status() == 205) {
  629. // 1. Run completionSteps.
  630. completion_steps();
  631. // 2. Return.
  632. return;
  633. }
  634. // FIXME: 10. Otherwise, if navigationParams's response has a `Content-Disposition`
  635. // header specifying the attachment disposition type, then:
  636. // 11. Otherwise:
  637. else {
  638. // 1. Let document be the result of loading a document given navigationParams, sourceSnapshotParams,
  639. // and entry's document state's initiator origin.
  640. auto document = load_document(navigation_params);
  641. // 2. If document is null, then run completionSteps and return.
  642. if (!document) {
  643. VERIFY_NOT_REACHED();
  644. completion_steps();
  645. return;
  646. }
  647. // 3. Set entry's document state's document to document.
  648. entry->document_state->set_document(document.ptr());
  649. // 4. Set entry's document state's origin to document's origin.
  650. entry->document_state->set_origin(document->origin());
  651. }
  652. // FIXME: 12. If entry's document state's request referrer is "client", then set it to request's referrer.
  653. // 13. If entry's document state's document is not null, then set entry's document state's ever populated to true.
  654. if (entry->document_state->document()) {
  655. entry->document_state->set_ever_populated(true);
  656. }
  657. // 14. Run completionSteps.
  658. completion_steps();
  659. });
  660. return {};
  661. }
  662. // To navigate a navigable navigable to a URL url using a Document sourceDocument,
  663. // with an optional POST resource, string, or null documentResource (default null),
  664. // an optional response-or-null response (default null), an optional boolean exceptionsEnabled (default false),
  665. // an optional history handling behavior historyHandling (default "push"),
  666. // an optional string cspNavigationType (default "other"),
  667. // and an optional referrer policy referrerPolicy (default the empty string):
  668. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
  669. WebIDL::ExceptionOr<void> Navigable::navigate(
  670. AK::URL const& url,
  671. JS::NonnullGCPtr<DOM::Document> source_document,
  672. Variant<Empty, String, POSTResource> document_resource,
  673. JS::GCPtr<Fetch::Infrastructure::Response> response,
  674. bool exceptions_enabled,
  675. HistoryHandlingBehavior history_handling,
  676. CSPNavigationType csp_navigation_type,
  677. ReferrerPolicy::ReferrerPolicy referrer_policy)
  678. {
  679. // 1. Let sourceSnapshotParams be the result of snapshotting source snapshot params given sourceDocument.
  680. auto source_snapshot_params = source_document->snapshot_source_snapshot_params();
  681. // 2. Let initiatorOriginSnapshot be sourceDocument's origin.
  682. auto initiator_origin_snapshot = source_document->origin();
  683. // FIXME: 3. If sourceDocument's node navigable is not allowed by sandboxing to navigate navigable given and sourceSnapshotParams, then:
  684. if constexpr (false) {
  685. // 1. If exceptionsEnabled is true, then throw a "SecurityError" DOMException.
  686. if (exceptions_enabled) {
  687. return WebIDL::SecurityError::create(*vm().current_realm(), "Source document's node navigable is not allowed to navigate"sv);
  688. }
  689. // 2 Return.
  690. return {};
  691. }
  692. // 4. Let navigationId be the result of generating a random UUID.
  693. String navigation_id = TRY_OR_THROW_OOM(vm(), Crypto::generate_random_uuid());
  694. // FIXME: 5. If the surrounding agent is equal to navigable's active document's relevant agent, then continue these steps.
  695. // Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to continue these steps.
  696. // FIXME: 6. If navigable's active document's unload counter is greater than 0,
  697. // then invoke WebDriver BiDi navigation failed with a WebDriver BiDi navigation status whose id is navigationId,
  698. // status is "canceled", and url is url, and return.
  699. // 7. If any of the following are true:
  700. // - url equals navigable's active document's URL;
  701. // - url's scheme is "javascript"; or
  702. // - navigable's active document's is initial about:blank is true
  703. if (url.equals(active_document()->url())
  704. || url.scheme() == "javascript"sv
  705. || active_document()->is_initial_about_blank()) {
  706. // then set historyHandling to "replace".
  707. history_handling = HistoryHandlingBehavior::Replace;
  708. }
  709. // 8. If all of the following are true:
  710. // - documentResource is null;
  711. // - response is null;
  712. // - url equals navigable's active session history entry's URL with exclude fragments set to true; and
  713. // - url's fragment is non-null
  714. if (document_resource.has<Empty>()
  715. && !response
  716. && url.equals(active_session_history_entry()->url, AK::URL::ExcludeFragment::Yes)
  717. && url.fragment().has_value()) {
  718. // 1. Navigate to a fragment given navigable, url, historyHandling, and navigationId.
  719. TRY(navigate_to_a_fragment(url, history_handling, navigation_id));
  720. // 2. Return.
  721. return {};
  722. }
  723. // 9. If navigable's parent is non-null, then set navigable's is delaying load events to true.
  724. if (parent() != nullptr) {
  725. set_delaying_load_events(true);
  726. }
  727. // 10. Let targetBrowsingContext be navigable's active browsing context.
  728. [[maybe_unused]] auto target_browsing_context = active_browsing_context();
  729. // FIXME: 11. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
  730. // FIXME: 12. 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".
  731. // 13. If navigable's ongoing navigation is "traversal", then:
  732. if (ongoing_navigation().has<Traversal>()) {
  733. // 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.
  734. // 2. Return.
  735. return {};
  736. }
  737. // 14. Set navigable's ongoing navigation to navigationId.
  738. m_ongoing_navigation = navigation_id;
  739. // 15. If url's scheme is "javascript", then:
  740. if (url.scheme() == "javascript"sv) {
  741. // 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.
  742. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this, url, history_handling, initiator_origin_snapshot, csp_navigation_type] {
  743. (void)navigate_to_a_javascript_url(url, history_handling, initiator_origin_snapshot, csp_navigation_type);
  744. });
  745. // 2. Return.
  746. return {};
  747. }
  748. // 16. In parallel, run these steps:
  749. 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] {
  750. // FIXME: 1. Let unloadPromptCanceled be the result of checking if unloading is user-canceled for navigable's active document's inclusive descendant navigables.
  751. // FIXME: 2. If unloadPromptCanceled is true, or navigable's ongoing navigation is no longer navigationId, then:
  752. if (!ongoing_navigation().has<String>() || ongoing_navigation().get<String>() != navigation_id) {
  753. // 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.
  754. // 2. Abort these steps.
  755. return;
  756. }
  757. // 3. Queue a global task on the navigation and traversal task source given navigable's active window to abort navigable's active document.
  758. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this] {
  759. VERIFY(active_document());
  760. active_document()->abort();
  761. });
  762. // 4. Let documentState be a new document state with
  763. // request referrer policy: referrerPolicy
  764. // initiator origin: initiatorOriginSnapshot
  765. // resource: documentResource
  766. // navigable target name: navigable's target name
  767. JS::NonnullGCPtr<DocumentState> document_state = *heap().allocate_without_realm<DocumentState>();
  768. document_state->set_request_referrer_policy(referrer_policy);
  769. document_state->set_resource(document_resource);
  770. document_state->set_initiator_origin(initiator_origin_snapshot);
  771. document_state->set_navigable_target_name(target_name());
  772. // 5. If url is about:blank, then set documentState's origin to documentState's initiator origin.
  773. if (url == "about:blank"sv) {
  774. document_state->set_origin(document_state->initiator_origin());
  775. }
  776. // 6. Otherwise, if url is about:srcdoc, then set documentState's origin to navigable's parent's active document's origin.
  777. else if (url == "about:srcdoc"sv) {
  778. document_state->set_origin(parent()->active_document()->origin());
  779. }
  780. // 7. Let historyEntry be a new session history entry, with its URL set to url and its document state set to documentState.
  781. JS::NonnullGCPtr<SessionHistoryEntry> history_entry = *heap().allocate_without_realm<SessionHistoryEntry>();
  782. history_entry->url = url;
  783. history_entry->document_state = document_state;
  784. // 8. Let navigationParams be null.
  785. Optional<NavigationParams> navigation_params;
  786. // FIXME: 9. If response is non-null:
  787. if (response) {
  788. }
  789. // 10. Attempt to populate the history entry's document
  790. // for historyEntry, given navigable, "navigate", sourceSnapshotParams,
  791. // targetSnapshotParams, navigationId, navigationParams, cspNavigationType, with allowPOST
  792. // set to true and completionSteps set to the following step:
  793. populate_session_history_entry_document(history_entry, navigation_params, navigation_id, source_snapshot_params, true, [this, history_entry, history_handling, navigation_id] {
  794. traversable_navigable()->append_session_history_traversal_steps([this, history_entry, history_handling, navigation_id] {
  795. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#finalize-a-cross-document-navigation
  796. // 1. FIXME: Assert: this is running on navigable's traversable navigable's session history traversal queue.
  797. // 2. Set navigable's is delaying load events to false.
  798. set_delaying_load_events(false);
  799. // 3. If historyEntry's document is null, then return.
  800. if (!history_entry->document_state->document())
  801. return;
  802. // 4. FIXME: If all of the following are true:
  803. // - navigable's parent is null;
  804. // - historyEntry's document's browsing context is not an auxiliary browsing context whose opener browsing context is non-null; and
  805. // - historyEntry's document's origin is not navigable's active document's origin
  806. // then set historyEntry's document state's navigable target name to the empty string.
  807. // 5. Let entryToReplace be navigable's active session history entry if historyHandling is "replace", otherwise null.
  808. auto entry_to_replace = history_handling == HistoryHandlingBehavior::Replace ? active_session_history_entry() : nullptr;
  809. // 6. Let traversable be navigable's traversable navigable.
  810. auto traversable = traversable_navigable();
  811. // 7. Let targetStep be null.
  812. int target_step;
  813. // 8. Let targetEntries be the result of getting session history entries for navigable.
  814. auto& target_entries = get_session_history_entries();
  815. // 9. If entryToReplace is null, then:
  816. if (entry_to_replace == nullptr) {
  817. // FIXME: 1. Clear the forward session history of traversable.
  818. traversable->clear_the_forward_session_history();
  819. // 2. Set targetStep to traversable's current session history step + 1.
  820. target_step = traversable->current_session_history_step() + 1;
  821. // 3. Set historyEntry's step to targetStep.
  822. history_entry->step = target_step;
  823. // 4. Append historyEntry to targetEntries.
  824. target_entries.append(move(history_entry));
  825. } else {
  826. // 1. Replace entryToReplace with historyEntry in targetEntries.
  827. *(target_entries.find(*entry_to_replace)) = history_entry;
  828. // 2. Set historyEntry's step to entryToReplace's step.
  829. history_entry->step = entry_to_replace->step;
  830. // 3. Set targetStep to traversable's current session history step.
  831. target_step = traversable->current_session_history_step();
  832. }
  833. // 10. Apply the history step targetStep to traversable.
  834. traversable->apply_the_history_step(target_step);
  835. });
  836. }).release_value_but_fixme_should_propagate_errors();
  837. });
  838. return {};
  839. }
  840. WebIDL::ExceptionOr<void> Navigable::navigate_to_a_fragment(AK::URL const& url, HistoryHandlingBehavior history_handling, String navigation_id)
  841. {
  842. (void)navigation_id;
  843. // FIXME: 1. Let navigation be navigable's active window's navigation API.
  844. // FIXME: 2. Let destinationNavigationAPIState be navigable's active session history entry's navigation API state.
  845. // FIXME: 3. If navigationAPIState is not null, then set destinationNavigationAPIState to navigationAPIState.
  846. // 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,
  847. // userInvolvement set to userInvolvement, and destinationURL set to url, and navigationAPIState set to destinationNavigationAPIState.
  848. // FIXME: 5. If continue is false, then return.
  849. // 6. Let historyEntry be a new session history entry, with
  850. // URL: url
  851. // document state: navigable's active session history entry's document state
  852. // navigation API state: destinationNavigationAPIState
  853. // scroll restoration mode: navigable's active session history entry's scroll restoration mode
  854. JS::NonnullGCPtr<SessionHistoryEntry> history_entry = heap().allocate_without_realm<SessionHistoryEntry>();
  855. history_entry->url = url;
  856. history_entry->document_state = active_session_history_entry()->document_state;
  857. history_entry->scroll_restoration_mode = active_session_history_entry()->scroll_restoration_mode;
  858. // 7. Let entryToReplace be navigable's active session history entry if historyHandling is "replace", otherwise null.
  859. auto entry_to_replace = history_handling == HistoryHandlingBehavior::Replace ? active_session_history_entry() : nullptr;
  860. // FIXME: 8. Let history be navigable's active document's history object.
  861. // FIXME: 9. Let scriptHistoryIndex be history's index.
  862. // FIXME: 10. Let scriptHistoryIndex be history's index.
  863. // 11. If historyHandling is "push", then:
  864. if (history_handling == HistoryHandlingBehavior::Push) {
  865. // FIXME: 1. Set history's state to null.
  866. // FIXME: 2. Increment scriptHistoryIndex.
  867. // FIXME: 3. Set scriptHistoryLength to scriptHistoryIndex + 1.
  868. }
  869. // 12. Set navigable's active session history entry to historyEntry.
  870. m_active_session_history_entry = history_entry;
  871. // FIXME: 13. Update document for history step application given navigable's active document, historyEntry, true, scriptHistoryIndex, and scriptHistoryLength.
  872. // FIXME: 14. Update the navigation API entries for a same-document navigation given navigation, historyEntry, and historyHandling.
  873. // 15. Scroll to the fragment given navigable's active document.
  874. // FIXME: Specification doesn't say when document url needs to update during fragment navigation
  875. active_document()->set_url(url);
  876. active_document()->scroll_to_the_fragment();
  877. // 16. Let traversable be navigable's traversable navigable.
  878. auto traversable = traversable_navigable();
  879. // 17. Append the following session history synchronous navigation steps involving navigable to traversable:
  880. traversable->append_session_history_traversal_steps([&] {
  881. // 1. Finalize a same-document navigation given traversable, navigable, historyEntry, and entryToReplace.
  882. finalize_a_same_document_navigation(*traversable, *this, history_entry, entry_to_replace);
  883. // FIXME: 2. Invoke WebDriver BiDi fragment navigated with navigable's active browsing context and a new WebDriver BiDi
  884. // navigation status whose id is navigationId, url is url, and status is "complete".
  885. });
  886. return {};
  887. }
  888. WebIDL::ExceptionOr<void> Navigable::navigate_to_a_javascript_url(AK::URL const&, HistoryHandlingBehavior, Origin const& initiator_origin, CSPNavigationType csp_navigation_type)
  889. {
  890. (void)initiator_origin;
  891. (void)csp_navigation_type;
  892. TODO();
  893. }
  894. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#reload
  895. void Navigable::reload()
  896. {
  897. // 1. Set navigable's active session history entry's document state's reload pending to true.
  898. active_session_history_entry()->document_state->set_reload_pending(true);
  899. // 2. Let traversable be navigable's traversable navigable.
  900. auto traversable = traversable_navigable();
  901. // 3. Append the following session history traversal steps to traversable:
  902. traversable->append_session_history_traversal_steps([traversable] {
  903. // 1. Apply pending history changes to traversable with true.
  904. traversable->apply_pending_history_changes();
  905. });
  906. }
  907. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#the-navigation-must-be-a-replace
  908. bool navigation_must_be_a_replace(AK::URL const& url, DOM::Document const& document)
  909. {
  910. return url.scheme() == "javascript"sv || document.is_initial_about_blank();
  911. }
  912. }