Navigable.cpp 61 KB

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