Navigable.cpp 60 KB

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