Navigable.cpp 78 KB

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