Navigable.cpp 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014
  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/HTMLIFrameElement.h>
  17. #include <LibWeb/HTML/HistoryHandlingBehavior.h>
  18. #include <LibWeb/HTML/Navigable.h>
  19. #include <LibWeb/HTML/Navigation.h>
  20. #include <LibWeb/HTML/NavigationParams.h>
  21. #include <LibWeb/HTML/POSTResource.h>
  22. #include <LibWeb/HTML/SandboxingFlagSet.h>
  23. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  24. #include <LibWeb/HTML/SessionHistoryEntry.h>
  25. #include <LibWeb/HTML/StructuredSerialize.h>
  26. #include <LibWeb/HTML/TraversableNavigable.h>
  27. #include <LibWeb/HTML/Window.h>
  28. #include <LibWeb/Infra/Strings.h>
  29. #include <LibWeb/Layout/Node.h>
  30. #include <LibWeb/Loader/GeneratedPagesLoader.h>
  31. #include <LibWeb/Page/Page.h>
  32. #include <LibWeb/Platform/EventLoopPlugin.h>
  33. #include <LibWeb/XHR/FormData.h>
  34. namespace Web::HTML {
  35. JS_DEFINE_ALLOCATOR(Navigable);
  36. class ResponseHolder : public JS::Cell {
  37. JS_CELL(ResponseHolder, JS::Cell);
  38. JS_DECLARE_ALLOCATOR(ResponseHolder);
  39. public:
  40. [[nodiscard]] static JS::NonnullGCPtr<ResponseHolder> create(JS::VM& vm)
  41. {
  42. return vm.heap().allocate_without_realm<ResponseHolder>();
  43. }
  44. [[nodiscard]] JS::GCPtr<Fetch::Infrastructure::Response> response() const { return m_response; }
  45. void set_response(JS::GCPtr<Fetch::Infrastructure::Response> response) { m_response = response; }
  46. virtual void visit_edges(Cell::Visitor& visitor) override
  47. {
  48. visitor.visit(m_response);
  49. }
  50. private:
  51. JS::GCPtr<Fetch::Infrastructure::Response> m_response;
  52. };
  53. JS_DEFINE_ALLOCATOR(ResponseHolder);
  54. HashTable<Navigable*>& all_navigables()
  55. {
  56. static HashTable<Navigable*> set;
  57. return set;
  58. }
  59. // https://html.spec.whatwg.org/multipage/document-sequences.html#child-navigable
  60. Vector<JS::Handle<Navigable>> Navigable::child_navigables() const
  61. {
  62. Vector<JS::Handle<Navigable>> results;
  63. for (auto& entry : all_navigables()) {
  64. if (entry->current_session_history_entry()->step == SessionHistoryEntry::Pending::Tag)
  65. continue;
  66. if (entry->parent() == this)
  67. results.append(entry);
  68. }
  69. return results;
  70. }
  71. bool Navigable::is_traversable() const
  72. {
  73. return is<TraversableNavigable>(*this);
  74. }
  75. Navigable::Navigable()
  76. {
  77. all_navigables().set(this);
  78. }
  79. Navigable::~Navigable()
  80. {
  81. all_navigables().remove(this);
  82. }
  83. void Navigable::visit_edges(Cell::Visitor& visitor)
  84. {
  85. Base::visit_edges(visitor);
  86. visitor.visit(m_parent);
  87. visitor.visit(m_current_session_history_entry);
  88. visitor.visit(m_active_session_history_entry);
  89. visitor.visit(m_container);
  90. }
  91. void Navigable::set_delaying_load_events(bool value)
  92. {
  93. if (value) {
  94. auto document = container_document();
  95. VERIFY(document);
  96. m_delaying_the_load_event.emplace(*document);
  97. } else {
  98. m_delaying_the_load_event.clear();
  99. }
  100. }
  101. JS::GCPtr<Navigable> Navigable::navigable_with_active_document(JS::NonnullGCPtr<DOM::Document> document)
  102. {
  103. for (auto* navigable : all_navigables()) {
  104. if (navigable->active_document() == document)
  105. return navigable;
  106. }
  107. return nullptr;
  108. }
  109. // https://html.spec.whatwg.org/multipage/document-sequences.html#initialize-the-navigable
  110. ErrorOr<void> Navigable::initialize_navigable(JS::NonnullGCPtr<DocumentState> document_state, JS::GCPtr<Navigable> parent)
  111. {
  112. static int next_id = 0;
  113. m_id = TRY(String::number(next_id++));
  114. // 1. Let entry be a new session history entry, with
  115. JS::NonnullGCPtr<SessionHistoryEntry> entry = *heap().allocate_without_realm<SessionHistoryEntry>();
  116. // URL: document's URL
  117. entry->url = document_state->document()->url();
  118. // document state: documentState
  119. entry->document_state = document_state;
  120. // 2. Set navigable's current session history entry to entry.
  121. m_current_session_history_entry = entry;
  122. // 3. Set navigable's active session history entry to entry.
  123. m_active_session_history_entry = entry;
  124. // 4. Set navigable's parent to parent.
  125. m_parent = parent;
  126. return {};
  127. }
  128. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-target-history-entry
  129. JS::GCPtr<SessionHistoryEntry> Navigable::get_the_target_history_entry(int target_step) const
  130. {
  131. // 1. Let entries be the result of getting session history entries for navigable.
  132. auto& entries = get_session_history_entries();
  133. // 2. Return the item in entries that has the greatest step less than or equal to step.
  134. JS::GCPtr<SessionHistoryEntry> result = nullptr;
  135. for (auto& entry : entries) {
  136. auto entry_step = entry->step.get<int>();
  137. if (entry_step <= target_step) {
  138. if (!result || result->step.get<int>() < entry_step) {
  139. result = entry;
  140. }
  141. }
  142. }
  143. return result;
  144. }
  145. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#activate-history-entry
  146. void Navigable::activate_history_entry(JS::GCPtr<SessionHistoryEntry> entry)
  147. {
  148. // FIXME: 1. Save persisted state to the navigable's active session history entry.
  149. // 2. Let newDocument be entry's document.
  150. JS::GCPtr<DOM::Document> new_document = entry->document_state->document().ptr();
  151. // 3. Assert: newDocument's is initial about:blank is false, i.e., we never traverse
  152. // back to the initial about:blank Document because it always gets replaced when we
  153. // navigate away from it.
  154. VERIFY(!new_document->is_initial_about_blank());
  155. // 4. Set navigable's active session history entry to entry.
  156. m_active_session_history_entry = entry;
  157. // 5. Make active newDocument.
  158. new_document->make_active();
  159. // Not in the spec:
  160. VERIFY(active_browsing_context());
  161. VERIFY(active_browsing_context()->page());
  162. active_browsing_context()->page()->client().page_did_create_new_document(*new_document);
  163. }
  164. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-document
  165. JS::GCPtr<DOM::Document> Navigable::active_document()
  166. {
  167. // A navigable's active document is its active session history entry's document.
  168. return m_active_session_history_entry->document_state->document();
  169. }
  170. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-bc
  171. JS::GCPtr<BrowsingContext> Navigable::active_browsing_context()
  172. {
  173. // A navigable's active browsing context is its active document's browsing context.
  174. // If this navigable is a traversable navigable, then its active browsing context will be a top-level browsing context.
  175. if (auto document = active_document())
  176. return document->browsing_context();
  177. return nullptr;
  178. }
  179. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-wp
  180. JS::GCPtr<HTML::WindowProxy> Navigable::active_window_proxy()
  181. {
  182. // A navigable's active WindowProxy is its active browsing context's associated WindowProxy.
  183. if (auto browsing_context = active_browsing_context())
  184. return browsing_context->window_proxy();
  185. return nullptr;
  186. }
  187. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-window
  188. JS::GCPtr<HTML::Window> Navigable::active_window()
  189. {
  190. // A navigable's active window is its active WindowProxy's [[Window]].
  191. if (auto window_proxy = active_window_proxy())
  192. return window_proxy->window();
  193. return nullptr;
  194. }
  195. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-target
  196. String Navigable::target_name() const
  197. {
  198. // A navigable's target name is its active session history entry's document state's navigable target name.
  199. return active_session_history_entry()->document_state->navigable_target_name();
  200. }
  201. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-container
  202. JS::GCPtr<NavigableContainer> Navigable::container() const
  203. {
  204. // The container of a navigable navigable is the navigable container whose nested navigable is navigable, or null if there is no such element.
  205. return NavigableContainer::navigable_container_with_content_navigable(const_cast<Navigable&>(*this));
  206. }
  207. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-container-document
  208. JS::GCPtr<DOM::Document> Navigable::container_document() const
  209. {
  210. auto container = this->container();
  211. // 1. If navigable's container is null, then return null.
  212. if (!container)
  213. return nullptr;
  214. // 2. Return navigable's container's node document.
  215. return container->document();
  216. }
  217. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-traversable
  218. JS::GCPtr<TraversableNavigable> Navigable::traversable_navigable() const
  219. {
  220. // 1. Let navigable be inputNavigable.
  221. auto navigable = const_cast<Navigable*>(this);
  222. // 2. While navigable is not a traversable navigable, set navigable to navigable's parent.
  223. while (navigable && !is<TraversableNavigable>(*navigable))
  224. navigable = navigable->parent();
  225. // 3. Return navigable.
  226. return static_cast<TraversableNavigable*>(navigable);
  227. }
  228. // https://html.spec.whatwg.org/multipage/document-sequences.html#nav-top
  229. JS::GCPtr<TraversableNavigable> Navigable::top_level_traversable()
  230. {
  231. // 1. Let navigable be inputNavigable.
  232. auto navigable = this;
  233. // 2. While navigable's parent is not null, set navigable to navigable's parent.
  234. while (navigable->parent())
  235. navigable = navigable->parent();
  236. // 3. Return navigable.
  237. return verify_cast<TraversableNavigable>(navigable);
  238. }
  239. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#set-the-ongoing-navigation
  240. void Navigable::set_ongoing_navigation(Variant<Empty, Traversal, String> ongoing_navigation)
  241. {
  242. // 1. If navigable's ongoing navigation is equal to newValue, then return.
  243. if (m_ongoing_navigation == ongoing_navigation)
  244. return;
  245. // 2. Inform the navigation API about aborting navigation given navigable.
  246. inform_the_navigation_api_about_aborting_navigation();
  247. // 3. Set navigable's ongoing navigation to newValue.
  248. m_ongoing_navigation = ongoing_navigation;
  249. }
  250. // https://html.spec.whatwg.org/multipage/document-sequences.html#the-rules-for-choosing-a-navigable
  251. Navigable::ChosenNavigable Navigable::choose_a_navigable(StringView name, TokenizedFeature::NoOpener no_opener, ActivateTab)
  252. {
  253. // 1. Let chosen be null.
  254. JS::GCPtr<Navigable> chosen = nullptr;
  255. // 2. Let windowType be "existing or none".
  256. auto window_type = WindowType::ExistingOrNone;
  257. // 3. Let sandboxingFlagSet be current's active document's active sandboxing flag set.
  258. auto sandboxing_flag_set = active_document()->active_sandboxing_flag_set();
  259. // 4. If name is the empty string or an ASCII case-insensitive match for "_self", then set chosen to currentNavigable.
  260. if (name.is_empty() || Infra::is_ascii_case_insensitive_match(name, "_self"sv)) {
  261. chosen = this;
  262. }
  263. // 5. Otherwise, if name is an ASCII case-insensitive match for "_parent",
  264. // set chosen to currentNavigable's parent, if any, and currentNavigable otherwise.
  265. else if (Infra::is_ascii_case_insensitive_match(name, "_parent"sv)) {
  266. if (auto parent = this->parent())
  267. chosen = parent;
  268. else
  269. chosen = this;
  270. }
  271. // 6. Otherwise, if name is an ASCII case-insensitive match for "_top",
  272. // set chosen to currentNavigable's traversable navigable.
  273. else if (Infra::is_ascii_case_insensitive_match(name, "_top"sv)) {
  274. chosen = traversable_navigable();
  275. }
  276. // FIXME: 7. Otherwise, if name is not an ASCII case-insensitive match for "_blank",
  277. // there exists a navigable whose target name is the same as name, currentNavigable's
  278. // active browsing context is familiar with that navigable's active browsing context,
  279. // and the user agent determines that the two browsing contexts are related enough that
  280. // it is ok if they reach each other, set chosen to that navigable. If there are multiple
  281. // matching navigables, the user agent should pick one in some arbitrary consistent manner,
  282. // such as the most recently opened, most recently focused, or more closely related, and set
  283. // chosen to it.
  284. // 8. Otherwise, a new top-level traversable is being requested, and what happens depends on the
  285. // user agent's configuration and abilities — it is determined by the rules given for the first
  286. // applicable option from the following list:
  287. else {
  288. // --> If current's active window does not have transient activation and the user agent has been configured to
  289. // not show popups (i.e., the user agent has a "popup blocker" enabled)
  290. if (!active_window()->has_transient_activation() && traversable_navigable()->page()->should_block_pop_ups()) {
  291. // FIXME: The user agent may inform the user that a popup has been blocked.
  292. dbgln("Pop-up blocked!");
  293. }
  294. // --> If sandboxingFlagSet has the sandboxed auxiliary navigation browsing context flag set
  295. else if (has_flag(sandboxing_flag_set, SandboxingFlagSet::SandboxedAuxiliaryNavigation)) {
  296. // FIXME: The user agent may report to a developer console that a popup has been blocked.
  297. dbgln("Pop-up blocked!");
  298. }
  299. // --> If the user agent has been configured such that in this instance it will create a new top-level traversable
  300. else if (true) { // FIXME: When is this the case?
  301. // 1. Set windowType to "new and unrestricted".
  302. window_type = WindowType::NewAndUnrestricted;
  303. // 2. Let currentDocument be currentNavigable's active document.
  304. auto current_document = active_document();
  305. // 3. If currentDocument's cross-origin opener policy's value is "same-origin" or "same-origin-plus-COEP",
  306. // and currentDocument's origin is not same origin with currentDocument's relevant settings object's top-level origin, then:
  307. if ((current_document->cross_origin_opener_policy().value == CrossOriginOpenerPolicyValue::SameOrigin || current_document->cross_origin_opener_policy().value == CrossOriginOpenerPolicyValue::SameOriginPlusCOEP)
  308. && !current_document->origin().is_same_origin(relevant_settings_object(*current_document).top_level_origin)) {
  309. // 1. Set noopener to true.
  310. no_opener = TokenizedFeature::NoOpener::Yes;
  311. // 2. Set name to "_blank".
  312. name = "_blank"sv;
  313. // 3. Set windowType to "new with no opener".
  314. window_type = WindowType::NewWithNoOpener;
  315. }
  316. // NOTE: In the presence of a cross-origin opener policy,
  317. // nested documents that are cross-origin with their top-level browsing context's active document always set noopener to true.
  318. // 4. Let chosen be null.
  319. chosen = nullptr;
  320. // 5. Let targetName be the empty string.
  321. String target_name;
  322. // 6. If name is not an ASCII case-insensitive match for "_blank", then set targetName to name.
  323. if (!Infra::is_ascii_case_insensitive_match(name, "_blank"sv))
  324. target_name = MUST(String::from_utf8(name));
  325. // 7. If noopener is true, then set chosen to the result of creating a new top-level traversable given null and targetName.
  326. if (no_opener == TokenizedFeature::NoOpener::Yes) {
  327. // FIXME: This should do something similar to RemoteBrowsingContext -- but RemoteTraversableNavigable instead
  328. TODO();
  329. }
  330. // 8. Otherwise:
  331. else {
  332. // 1. Set chosen to the result of creating a new top-level traversable given currentNavigable's active browsing context and targetName.
  333. // FIXME: Make this method return WebIDL::ExceptionOr<ChosenNavigable>
  334. chosen = TraversableNavigable::create_a_new_top_level_traversable(*traversable_navigable()->page(), active_browsing_context(), target_name).release_value_but_fixme_should_propagate_errors();
  335. // FIXME: 2. If sandboxingFlagSet's sandboxed navigation browsing context flag is set,
  336. // then set chosen's active browsing context's one permitted sandboxed navigator to currentNavigable's active browsing context.
  337. }
  338. // FIXME: 5. If sandboxingFlagSet's sandbox propagates to auxiliary browsing contexts flag is set,
  339. // then all the flags that are set in sandboxingFlagSet must be set in chosen's active browsing context's popup sandboxing flag set.
  340. // Our BrowsingContexts do not have SandboxingFlagSets yet, only documents do
  341. }
  342. // --> If the user agent has been configured such that in this instance t will reuse current
  343. else if (false) { // FIXME: When is this the case?
  344. // Set chosen to current.
  345. chosen = *this;
  346. }
  347. // --> If the user agent has been configured such that in this instance it will not find a browsing context
  348. else if (false) { // FIXME: When is this the case?
  349. // Do nothing.
  350. }
  351. }
  352. return { chosen.ptr(), window_type };
  353. }
  354. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-session-history-entries
  355. Vector<JS::NonnullGCPtr<SessionHistoryEntry>>& Navigable::get_session_history_entries() const
  356. {
  357. // 1. Let traversable be navigable's traversable navigable.
  358. auto traversable = traversable_navigable();
  359. // FIXME 2. Assert: this is running within traversable's session history traversal queue.
  360. // 3. If navigable is traversable, return traversable's session history entries.
  361. if (this == traversable)
  362. return traversable->session_history_entries();
  363. // 4. Let docStates be an empty ordered set of document states.
  364. Vector<JS::GCPtr<DocumentState>> doc_states;
  365. // 5. For each entry of traversable's session history entries, append entry's document state to docStates.
  366. for (auto& entry : traversable->session_history_entries())
  367. doc_states.append(entry->document_state);
  368. // 6. For each docState of docStates:
  369. while (!doc_states.is_empty()) {
  370. auto doc_state = doc_states.take_first();
  371. // 1. For each nestedHistory of docState's nested histories:
  372. for (auto& nested_history : doc_state->nested_histories()) {
  373. // 1. If nestedHistory's id equals navigable's id, return nestedHistory's entries.
  374. if (nested_history.id == id())
  375. return nested_history.entries;
  376. // 2. For each entry of nestedHistory's entries, append entry's document state to docStates.
  377. for (auto& entry : nested_history.entries)
  378. doc_states.append(entry->document_state);
  379. }
  380. }
  381. VERIFY_NOT_REACHED();
  382. }
  383. // https://html.spec.whatwg.org/multipage/browsers.html#determining-navigation-params-policy-container
  384. static PolicyContainer determine_navigation_params_policy_container(AK::URL const& response_url,
  385. Optional<PolicyContainer> history_policy_container,
  386. Optional<PolicyContainer> initiator_policy_container,
  387. Optional<PolicyContainer> parent_policy_container,
  388. Optional<PolicyContainer> response_policy_container)
  389. {
  390. // NOTE: The clone a policy container AO is just a C++ copy
  391. // 1. If historyPolicyContainer is not null, then:
  392. if (history_policy_container.has_value()) {
  393. // FIXME: 1. Assert: responseURL requires storing the policy container in history.
  394. // 2. Return a clone of historyPolicyContainer.
  395. return *history_policy_container;
  396. }
  397. // 2. If responseURL is about:srcdoc, then:
  398. if (response_url == "about:srcdoc"sv) {
  399. // 1. Assert: parentPolicyContainer is not null.
  400. VERIFY(parent_policy_container.has_value());
  401. // 2. Return a clone of parentPolicyContainer.
  402. return *parent_policy_container;
  403. }
  404. // 3. If responseURL is local and initiatorPolicyContainer is not null, then return a clone of initiatorPolicyContainer.
  405. if (Fetch::Infrastructure::is_local_url(response_url) && initiator_policy_container.has_value())
  406. return *initiator_policy_container;
  407. // 4. If responsePolicyContainer is not null, then return responsePolicyContainer.
  408. // FIXME: File a spec issue to say "a clone of" here for consistency
  409. if (response_policy_container.has_value())
  410. return *response_policy_container;
  411. // 5. Return a new policy container.
  412. return {};
  413. }
  414. // https://html.spec.whatwg.org/multipage/browsers.html#obtain-coop
  415. static CrossOriginOpenerPolicy obtain_a_cross_origin_opener_policy(JS::NonnullGCPtr<Fetch::Infrastructure::Response>, Fetch::Infrastructure::Request::ReservedClientType const& reserved_client)
  416. {
  417. // 1. Let policy be a new cross-origin opener policy.
  418. CrossOriginOpenerPolicy policy = {};
  419. // AD-HOC: We don't yet setup environments in all cases
  420. if (reserved_client.has<Empty>())
  421. return policy;
  422. auto& reserved_environment = reserved_client.visit(
  423. [](Empty const&) -> Environment& { VERIFY_NOT_REACHED(); },
  424. [](Environment* env) -> Environment& { return *env; },
  425. [](JS::GCPtr<EnvironmentSettingsObject> eso) -> Environment& { return *eso; });
  426. // 2. If reservedEnvironment is a non-secure context, then return policy.
  427. if (is_non_secure_context(reserved_environment))
  428. return policy;
  429. // FIXME: We don't yet have the technology to extract structured data from Fetch headers
  430. // FIXME: 3. Let parsedItem be the result of getting a structured field value given `Cross-Origin-Opener-Policy` and "item" from response's header list.
  431. // FIXME: 4. If parsedItem is not null, then:
  432. // FIXME: nested steps...
  433. // FIXME: 5. Set parsedItem to the result of getting a structured field value given `Cross-Origin-Opener-Policy-Report-Only` and "item" from response's header list.
  434. // FIXME: 6. If parsedItem is not null, then:
  435. // FIXME: nested steps...
  436. // 7. Return policy.
  437. return policy;
  438. }
  439. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#attempt-to-create-a-non-fetch-scheme-document
  440. static JS::GCPtr<DOM::Document> attempt_to_create_a_non_fetch_scheme_document(NonFetchSchemeNavigationParams const& params)
  441. {
  442. // FIXME: Implement this algorithm to hand off to external software or display inline content
  443. dbgln("(FIXME) Don't know how to navigate to {}", params.url);
  444. return nullptr;
  445. }
  446. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-from-a-srcdoc-resource
  447. static WebIDL::ExceptionOr<NavigationParams> create_navigation_params_from_a_srcdoc_resource(JS::GCPtr<SessionHistoryEntry> entry, JS::GCPtr<Navigable> navigable, TargetSnapshotParams const& target_snapshot_params, Optional<String> navigation_id)
  448. {
  449. auto& vm = navigable->vm();
  450. auto& realm = navigable->active_window()->realm();
  451. // 1. Let documentResource be entry's document state's resource.
  452. auto document_resource = entry->document_state->resource();
  453. VERIFY(document_resource.has<String>());
  454. // 2. Let response be a new response with
  455. // URL: about:srcdoc
  456. // header list: (`Content-Type`, `text/html`)
  457. // body: the UTF-8 encoding of documentResource, as a body
  458. auto response = Fetch::Infrastructure::Response::create(vm);
  459. response->url_list().append(AK::URL("about:srcdoc"));
  460. auto header = TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html"sv));
  461. TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
  462. response->set_body(TRY(Fetch::Infrastructure::byte_sequence_as_body(realm, document_resource.get<String>().bytes())));
  463. // 3. Let responseOrigin be the result of determining the origin given response's URL, targetSnapshotParams's sandboxing flags, and entry's document state's origin.
  464. auto response_origin = determine_the_origin(*response->url(), target_snapshot_params.sandboxing_flags, entry->document_state->origin());
  465. // 4. Let coop be a new cross-origin opener policy.
  466. CrossOriginOpenerPolicy coop = {};
  467. // 5. Let coopEnforcementResult be a new cross-origin opener policy enforcement result with
  468. // url: response's URL
  469. // origin: responseOrigin
  470. // cross-origin opener policy: coop
  471. CrossOriginOpenerPolicyEnforcementResult coop_enforcement_result {
  472. .url = *response->url(),
  473. .origin = response_origin,
  474. .cross_origin_opener_policy = coop
  475. };
  476. // 6. Let policyContainer be the result of determining navigation params policy container given response's URL,
  477. // entry's document state's history policy container, null, navigable's container document's policy container, and null.
  478. Optional<PolicyContainer> history_policy_container = entry->document_state->history_policy_container().visit(
  479. [](PolicyContainer const& c) -> Optional<PolicyContainer> { return c; },
  480. [](DocumentState::Client) -> Optional<PolicyContainer> { return {}; });
  481. PolicyContainer policy_container;
  482. if (navigable->container()) {
  483. // NOTE: Specification assumes that only navigables corresponding to iframes can be navigated to about:srcdoc.
  484. // We also use srcdoc to implement load_html() for top level navigables so we need to null check container
  485. // because it might be null.
  486. policy_container = determine_navigation_params_policy_container(*response->url(), history_policy_container, {}, navigable->container_document()->policy_container(), {});
  487. }
  488. // 7. Return a new navigation params, with
  489. // id: navigationId
  490. // navigable: navigable
  491. // request: null
  492. // response: response
  493. // fetch controller: null
  494. // commit early hints: null
  495. // COOP enforcement result: coopEnforcementResult
  496. // reserved environment: null
  497. // origin: responseOrigin
  498. // policy container: policyContainer
  499. // final sandboxing flag set: targetSnapshotParams's sandboxing flags
  500. // cross-origin opener policy: coop
  501. // FIXME: navigation timing type: navTimingType
  502. // about base URL: entry's document state's about base URL
  503. return NavigationParams {
  504. .id = move(navigation_id),
  505. .navigable = navigable,
  506. .request = nullptr,
  507. .response = *response,
  508. .fetch_controller = nullptr,
  509. .commit_early_hints = nullptr,
  510. .coop_enforcement_result = move(coop_enforcement_result),
  511. .reserved_environment = {},
  512. .origin = move(response_origin),
  513. .policy_container = policy_container,
  514. .final_sandboxing_flag_set = target_snapshot_params.sandboxing_flags,
  515. .cross_origin_opener_policy = move(coop),
  516. .about_base_url = entry->document_state->about_base_url(),
  517. };
  518. }
  519. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#create-navigation-params-by-fetching
  520. static WebIDL::ExceptionOr<Variant<Empty, NavigationParams, NonFetchSchemeNavigationParams>> create_navigation_params_by_fetching(JS::GCPtr<SessionHistoryEntry> entry, JS::GCPtr<Navigable> navigable, SourceSnapshotParams const& source_snapshot_params, TargetSnapshotParams const& target_snapshot_params, CSPNavigationType csp_navigation_type, Optional<String> navigation_id)
  521. {
  522. auto& vm = navigable->vm();
  523. auto& realm = navigable->active_window()->realm();
  524. auto& active_document = *navigable->active_document();
  525. (void)csp_navigation_type;
  526. // FIXME: 1. Assert: this is running in parallel.
  527. // 2. Let documentResource be entry's document state's resource.
  528. auto document_resource = entry->document_state->resource();
  529. // 3. Let request be a new request, with
  530. // url: entry's URL
  531. // client: sourceSnapshotParams's fetch client
  532. // destination: "document"
  533. // credentials mode: "include"
  534. // use-URL-credentials flag: set
  535. // redirect mode: "manual"
  536. // replaces client id: navigable's active document's relevant settings object's id
  537. // mode: "navigate"
  538. // referrer: entry's document state's request referrer
  539. // referrer policy: entry's document state's request referrer policy
  540. auto request = Fetch::Infrastructure::Request::create(vm);
  541. request->set_url(entry->url);
  542. request->set_client(source_snapshot_params.fetch_client);
  543. request->set_destination(Fetch::Infrastructure::Request::Destination::Document);
  544. request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::Include);
  545. request->set_use_url_credentials(true);
  546. request->set_redirect_mode(Fetch::Infrastructure::Request::RedirectMode::Manual);
  547. auto replaces_client_id = TRY_OR_THROW_OOM(vm, String::from_deprecated_string(active_document.relevant_settings_object().id));
  548. request->set_replaces_client_id(replaces_client_id);
  549. request->set_mode(Fetch::Infrastructure::Request::Mode::Navigate);
  550. request->set_referrer(entry->document_state->request_referrer());
  551. // 4. If documentResource is a POST resource, then:
  552. if (document_resource.has<POSTResource>()) {
  553. // 1. Set request's method to `POST`.
  554. request->set_method(TRY_OR_THROW_OOM(vm, ByteBuffer::copy("POST"sv.bytes())));
  555. // 2. Set request's body to documentResource's request body.
  556. request->set_body(document_resource.get<POSTResource>().request_body.value());
  557. // 3. Set `Content-Type` to documentResource's request content-type in request's header list.
  558. auto request_content_type = document_resource.get<POSTResource>().request_content_type;
  559. auto request_content_type_string = [request_content_type]() {
  560. switch (request_content_type) {
  561. case POSTResource::RequestContentType::ApplicationXWWWFormUrlencoded:
  562. return "application/x-www-form-urlencoded"sv;
  563. case POSTResource::RequestContentType::MultipartFormData:
  564. return "multipart/form-data"sv;
  565. case POSTResource::RequestContentType::TextPlain:
  566. return "text/plain"sv;
  567. default:
  568. VERIFY_NOT_REACHED();
  569. }
  570. }();
  571. auto header = TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, request_content_type_string));
  572. TRY_OR_THROW_OOM(vm, request->header_list()->append(move(header)));
  573. }
  574. // 5. If entry's document state's reload pending is true, then set request's reload-navigation flag.
  575. if (entry->document_state->reload_pending())
  576. request->set_reload_navigation(true);
  577. // 6. Otherwise, if entry's document state's ever populated is true, then set request's history-navigation flag.
  578. if (entry->document_state->ever_populated())
  579. request->set_history_navigation(true);
  580. // 7. If sourceSnapshotParams's has transient activation is true, then set request's user-activation to true.
  581. if (source_snapshot_params.has_transient_activation)
  582. request->set_user_activation(true);
  583. // 8. If navigable's container is non-null:
  584. if (navigable->container() != nullptr) {
  585. // 1. If the navigable's container has a browsing context scope origin, then set request's origin to that browsing context scope origin.
  586. // FIXME: From "browsing context scope origin": This definition is broken and needs investigation to see what it was intended to express: see issue #4703.
  587. // The referenced issue suggests that it is a no-op to retrieve the browsing context scope origin.
  588. // 2. Set request's destination to navigable's container's local name.
  589. // FIXME: Are there other container types? If so, we need a helper here
  590. Web::Fetch::Infrastructure::Request::Destination destination = is<HTMLIFrameElement>(*navigable->container()) ? Web::Fetch::Infrastructure::Request::Destination::IFrame
  591. : Web::Fetch::Infrastructure::Request::Destination::Object;
  592. request->set_destination(destination);
  593. // 3. If sourceSnapshotParams's fetch client is navigable's container document's relevant settings object,
  594. // then set request's initiator type to navigable's container's local name.
  595. // NOTE: This ensure that only container-initiated navigations are reported to resource timing.
  596. if (source_snapshot_params.fetch_client == &navigable->container_document()->relevant_settings_object()) {
  597. // FIXME: Are there other container types? If so, we need a helper here
  598. Web::Fetch::Infrastructure::Request::InitiatorType initiator_type = is<HTMLIFrameElement>(*navigable->container()) ? Web::Fetch::Infrastructure::Request::InitiatorType::IFrame
  599. : Web::Fetch::Infrastructure::Request::InitiatorType::Object;
  600. request->set_initiator_type(initiator_type);
  601. }
  602. }
  603. // 9. Let response be null.
  604. // NOTE: We use a heap-allocated cell to hold the response pointer because the processResponse callback below
  605. // might use it after this stack is freed.
  606. auto response_holder = ResponseHolder::create(vm);
  607. // 10. Let responseOrigin be null.
  608. Optional<HTML::Origin> response_origin;
  609. // 11. Let fetchController be null.
  610. JS::GCPtr<Fetch::Infrastructure::FetchController> fetch_controller = nullptr;
  611. // 12. Let coopEnforcementResult be a new cross-origin opener policy enforcement result, with
  612. // - url: navigable's active document's URL
  613. // - origin: navigable's active document's origin
  614. // - cross-origin opener policy: navigable's active document's cross-origin opener policy
  615. // - current context is navigation source: true if navigable's active document's origin is same origin with
  616. // entry's document state's initiator origin otherwise false
  617. CrossOriginOpenerPolicyEnforcementResult coop_enforcement_result = {
  618. .url = active_document.url(),
  619. .origin = active_document.origin(),
  620. .cross_origin_opener_policy = active_document.cross_origin_opener_policy(),
  621. .current_context_is_navigation_source = entry->document_state->initiator_origin().has_value() && active_document.origin().is_same_origin(*entry->document_state->initiator_origin())
  622. };
  623. // 13. Let finalSandboxFlags be an empty sandboxing flag set.
  624. SandboxingFlagSet final_sandbox_flags = {};
  625. // 14. Let responsePolicyContainer be null.
  626. Optional<PolicyContainer> response_policy_container = {};
  627. // 15. Let responseCOOP be a new cross-origin opener policy.
  628. CrossOriginOpenerPolicy response_coop = {};
  629. // 16. Let locationURL be null.
  630. ErrorOr<Optional<AK::URL>> location_url { OptionalNone {} };
  631. // 17. Let currentURL be request's current URL.
  632. AK::URL current_url = request->current_url();
  633. // 18. Let commitEarlyHints be null.
  634. Function<void(DOM::Document&)> commit_early_hints = nullptr;
  635. // 19. While true:
  636. while (true) {
  637. // 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:
  638. // FIXME: 2. If request's reserved client is null, then:
  639. // 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]
  640. // 4. Set response to null.
  641. response_holder->set_response(nullptr);
  642. // 5. If fetchController is null, then set fetchController to the result of fetching request,
  643. // with processEarlyHintsResponse set to processEarlyHintsResponseas defined below, processResponse
  644. // set to processResponse as defined below, and useParallelQueue set to true.
  645. if (!fetch_controller) {
  646. // FIXME: Let processEarlyHintsResponse be the following algorithm given a response earlyResponse:
  647. // Let processResponse be the following algorithm given a response fetchedResponse:
  648. auto process_response = [response_holder](JS::NonnullGCPtr<Fetch::Infrastructure::Response> fetch_response) {
  649. // 1. Set response to fetchedResponse.
  650. response_holder->set_response(fetch_response);
  651. };
  652. fetch_controller = TRY(Fetch::Fetching::fetch(
  653. realm,
  654. request,
  655. Fetch::Infrastructure::FetchAlgorithms::create(vm,
  656. {
  657. .process_request_body_chunk_length = {},
  658. .process_request_end_of_body = {},
  659. .process_early_hints_response = {},
  660. .process_response = move(process_response),
  661. .process_response_end_of_body = {},
  662. .process_response_consume_body = {},
  663. }),
  664. Fetch::Fetching::UseParallelQueue::Yes));
  665. }
  666. // 6. Otherwise, process the next manual redirect for fetchController.
  667. else {
  668. fetch_controller->process_next_manual_redirect();
  669. }
  670. // 7. Wait until either response is non-null, or navigable's ongoing navigation changes to no longer equal navigationId.
  671. Platform::EventLoopPlugin::the().spin_until([&]() {
  672. if (response_holder->response() != nullptr)
  673. return true;
  674. if (navigation_id.has_value() && (!navigable->ongoing_navigation().has<String>() || navigable->ongoing_navigation().get<String>() != *navigation_id))
  675. return true;
  676. return false;
  677. });
  678. // If the latter condition occurs, then abort fetchController, and return. Otherwise, proceed onward.
  679. if (navigation_id.has_value() && (!navigable->ongoing_navigation().has<String>() || navigable->ongoing_navigation().get<String>() != *navigation_id)) {
  680. fetch_controller->abort(realm, {});
  681. return Empty {};
  682. }
  683. // 8. If request's body is null, then set entry's document state's resource to null.
  684. if (!request->body().has<Empty>()) {
  685. entry->document_state->set_resource(Empty {});
  686. }
  687. // FIXME 9. Set responsePolicyContainer to the result of creating a policy container from a fetch response given response and request's reserved client.
  688. // FIXME 10. Set finalSandboxFlags to the union of targetSnapshotParams's sandboxing flags and responsePolicyContainer's CSP list's CSP-derived sandboxing flags.
  689. // 11. Set responseOrigin to the result of determining the origin given response's URL, finalSandboxFlags, and entry's document state's initiator origin.
  690. response_origin = determine_the_origin(*response_holder->response()->url(), final_sandbox_flags, entry->document_state->initiator_origin());
  691. // 12. If navigable is a top-level traversable, then:
  692. if (navigable->is_top_level_traversable()) {
  693. // 1. Set responseCOOP to the result of obtaining a cross-origin opener policy given response and request's reserved client.
  694. response_coop = obtain_a_cross_origin_opener_policy(*response_holder->response(), request->reserved_client());
  695. // FIXME: 2. Set coopEnforcementResult to the result of enforcing the response's cross-origin opener policy given navigable's active browsing context,
  696. // response's URL, responseOrigin, responseCOOP, coopEnforcementResult and request's referrer.
  697. // FIXME: 3. If finalSandboxFlags is not empty and responseCOOP's value is not "unsafe-none", then set response to an appropriate network error and break.
  698. // NOTE: This results in a network error as one cannot simultaneously provide a clean slate to a response
  699. // using cross-origin opener policy and sandbox the result of navigating to that response.
  700. }
  701. // 13. FIXME If response is not a network error, navigable is a child navigable, and the result of performing a cross-origin resource policy check
  702. // with navigable's container document's origin, navigable's container document's relevant settings object, request's destination, response,
  703. // and true is blocked, then set response to a network error and break.
  704. // NOTE: Here we're running the cross-origin resource policy check against the parent navigable rather than navigable itself
  705. // This is because we care about the same-originness of the embedded content against the parent context, not the navigation source.
  706. // 14. Set locationURL to response's location URL given currentURL's fragment.
  707. auto location_url = response_holder->response()->location_url(current_url.fragment());
  708. VERIFY(!location_url.is_error());
  709. // 15. If locationURL is failure or null, then break.
  710. if (location_url.is_error() || !location_url.value().has_value()) {
  711. break;
  712. }
  713. // 16. Assert: locationURL is a URL.
  714. VERIFY(location_url.value()->is_valid());
  715. // 17. Set entry's classic history API state to StructuredSerializeForStorage(null).
  716. entry->classic_history_api_state = MUST(structured_serialize_for_storage(vm, JS::js_null()));
  717. // 18. Let oldDocState be entry's document state.
  718. auto old_doc_state = entry->document_state;
  719. // 19. Set entry's document state to a new document state, with
  720. // history policy container: a clone of the oldDocState's history policy container if it is non-null; null otherwise
  721. // request referrer: oldDocState's request referrer
  722. // request referrer policy: oldDocState's request referrer policy
  723. // origin: oldDocState's origin
  724. // resource: oldDocState's resource
  725. // ever populated: oldDocState's ever populated
  726. // navigable target name: oldDocState's navigable target name
  727. entry->document_state = navigable->heap().allocate_without_realm<DocumentState>();
  728. entry->document_state->set_history_policy_container(old_doc_state->history_policy_container());
  729. entry->document_state->set_request_referrer(old_doc_state->request_referrer());
  730. entry->document_state->set_request_referrer_policy(old_doc_state->request_referrer_policy());
  731. entry->document_state->set_origin(old_doc_state->origin());
  732. entry->document_state->set_resource(old_doc_state->resource());
  733. entry->document_state->set_ever_populated(old_doc_state->ever_populated());
  734. entry->document_state->set_navigable_target_name(old_doc_state->navigable_target_name());
  735. // 20. If locationURL's scheme is not an HTTP(S) scheme, then:
  736. if (!Fetch::Infrastructure::is_http_or_https_scheme(location_url.value()->scheme())) {
  737. // 1. Set entry's document state's resource to null.
  738. entry->document_state->set_resource(Empty {});
  739. // 2. Break.
  740. break;
  741. }
  742. // 21. Set currentURL to locationURL.
  743. current_url = location_url.value().value();
  744. // 22. Set entry's URL to currentURL.
  745. entry->url = current_url;
  746. }
  747. // 20. If locationURL is a URL whose scheme is not a fetch scheme, then return a new non-fetch scheme navigation params, with
  748. if (!location_url.is_error() && location_url.value().has_value() && !Fetch::Infrastructure::is_fetch_scheme(location_url.value().value().scheme())) {
  749. // - id: navigationId
  750. // - navigable: navigable
  751. // - URL: locationURL
  752. // - target snapshot sandboxing flags: targetSnapshotParams's sandboxing flags
  753. // - source snapshot has transient activation: sourceSnapshotParams's has transient activation
  754. // - initiator origin: responseOrigin
  755. // FIXME: - navigation timing type: navTimingType
  756. return NonFetchSchemeNavigationParams {
  757. .id = navigation_id,
  758. .navigable = navigable,
  759. .url = location_url.release_value().value(),
  760. .target_snapshot_sandboxing_flags = target_snapshot_params.sandboxing_flags,
  761. .source_snapshot_has_transient_activation = source_snapshot_params.has_transient_activation,
  762. .initiator_origin = move(*response_origin),
  763. };
  764. }
  765. // 21. If any of the following are true:
  766. // - response is a network error;
  767. // - locationURL is failure; or
  768. // - locationURL is a URL whose scheme is a fetch scheme
  769. // then return null.
  770. 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()))) {
  771. return Empty {};
  772. }
  773. // 22. Assert: locationURL is null and response is not a network error.
  774. VERIFY(!location_url.value().has_value());
  775. VERIFY(!response_holder->response()->is_network_error());
  776. // 23. Let resultPolicyContainer be the result of determining navigation params policy container given response's URL,
  777. // entry's document state's history policy container, sourceSnapshotParams's source policy container, null, and responsePolicyContainer.
  778. Optional<PolicyContainer> history_policy_container = entry->document_state->history_policy_container().visit(
  779. [](PolicyContainer const& c) -> Optional<PolicyContainer> { return c; },
  780. [](DocumentState::Client) -> Optional<PolicyContainer> { return {}; });
  781. auto result_policy_container = determine_navigation_params_policy_container(*response_holder->response()->url(), history_policy_container, source_snapshot_params.source_policy_container, {}, response_policy_container);
  782. // 24. If navigable's container is an iframe, and response's timing allow passed flag is set, then set container's pending resource-timing start time to null.
  783. if (navigable->container() && is<HTML::HTMLIFrameElement>(*navigable->container()) && response_holder->response()->timing_allow_passed())
  784. static_cast<HTML::HTMLIFrameElement&>(*navigable->container()).set_pending_resource_start_time({});
  785. // 25. Return a new navigation params, with
  786. // id: navigationId
  787. // navigable: navigable
  788. // request: request
  789. // response: response
  790. // fetch controller: fetchController
  791. // commit early hints: commitEarlyHints
  792. // cross-origin opener policy: responseCOOP
  793. // reserved environment: request's reserved client
  794. // origin: responseOrigin
  795. // policy container: resultPolicyContainer
  796. // final sandboxing flag set: finalSandboxFlags
  797. // COOP enforcement result: coopEnforcementResult
  798. // FIXME: navigation timing type: navTimingType
  799. // about base URL: entry's document state's about base URL
  800. HTML::NavigationParams navigation_params {
  801. .id = navigation_id,
  802. .navigable = navigable,
  803. .request = request,
  804. .response = *response_holder->response(),
  805. .fetch_controller = fetch_controller,
  806. .commit_early_hints = move(commit_early_hints),
  807. .coop_enforcement_result = coop_enforcement_result,
  808. .reserved_environment = request->reserved_client(),
  809. .origin = *response_origin,
  810. .policy_container = result_policy_container,
  811. .final_sandboxing_flag_set = final_sandbox_flags,
  812. .cross_origin_opener_policy = response_coop,
  813. .about_base_url = entry->document_state->about_base_url(),
  814. };
  815. return navigation_params;
  816. }
  817. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#attempt-to-populate-the-history-entry's-document
  818. WebIDL::ExceptionOr<void> Navigable::populate_session_history_entry_document(
  819. JS::GCPtr<SessionHistoryEntry> entry,
  820. SourceSnapshotParams const& source_snapshot_params,
  821. TargetSnapshotParams const& target_snapshot_params,
  822. Optional<String> navigation_id,
  823. Variant<Empty, NavigationParams, NonFetchSchemeNavigationParams> navigation_params,
  824. CSPNavigationType csp_navigation_type,
  825. bool allow_POST,
  826. Function<void()> completion_steps)
  827. {
  828. // FIXME: 1. Assert: this is running in parallel.
  829. // 2. Assert: if navigationParams is non-null, then navigationParams's response is non-null.
  830. // NavigationParams' response field is NonnullGCPtr
  831. if (!navigation_params.has<Empty>())
  832. VERIFY(navigation_params.has<NavigationParams>());
  833. // 3. Let currentBrowsingContext be navigable's active browsing context.
  834. [[maybe_unused]] auto current_browsing_context = active_browsing_context();
  835. // 4. Let documentResource be entry's document state's resource.
  836. auto document_resource = entry->document_state->resource();
  837. // 5. If navigationParams is null, then:
  838. if (navigation_params.has<Empty>()) {
  839. // 1. If documentResource is a string, then set navigationParams to the result
  840. // of creating navigation params from a srcdoc resource given entry, navigable,
  841. // targetSnapshotParams, navigationId, and navTimingType.
  842. if (document_resource.has<String>()) {
  843. navigation_params = TRY(create_navigation_params_from_a_srcdoc_resource(entry, this, target_snapshot_params, navigation_id));
  844. }
  845. // 2. Otherwise, if both of the following are true:
  846. // - entry's URL's scheme is a fetch scheme; and
  847. // - documentResource is null, or allowPOST is true and documentResource's request body is not failure (FIXME: check if request body is not failure)
  848. else if (Fetch::Infrastructure::is_fetch_scheme(entry->url.scheme()) && (document_resource.has<Empty>() || allow_POST)) {
  849. navigation_params = TRY(create_navigation_params_by_fetching(entry, this, source_snapshot_params, target_snapshot_params, csp_navigation_type, navigation_id));
  850. }
  851. // 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:
  852. else if (!Fetch::Infrastructure::is_fetch_scheme(entry->url.scheme())) {
  853. // - id: navigationId
  854. // - navigable: navigable
  855. // - URL: entry's URL
  856. // - target snapshot sandboxing flags: targetSnapshotParams's sandboxing flags
  857. // - source snapshot has transient activation: sourceSnapshotParams's has transient activation
  858. // - initiator origin: entry's document state's initiator origin
  859. // FIXME: - navigation timing type: navTimingType
  860. navigation_params = NonFetchSchemeNavigationParams {
  861. .id = navigation_id,
  862. .navigable = this,
  863. .url = entry->url,
  864. .target_snapshot_sandboxing_flags = target_snapshot_params.sandboxing_flags,
  865. .source_snapshot_has_transient_activation = source_snapshot_params.has_transient_activation,
  866. .initiator_origin = *entry->document_state->initiator_origin(),
  867. };
  868. }
  869. }
  870. // NOTE: Not in the spec but queuing task on the next step will fail because active_window() does not exist for destroyed navigable.
  871. if (has_been_destroyed())
  872. return {};
  873. // 6. Queue a global task on the navigation and traversal task source, given navigable's active window, to run these steps:
  874. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this, entry, navigation_params = move(navigation_params), navigation_id, completion_steps = move(completion_steps)]() mutable {
  875. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  876. if (has_been_destroyed())
  877. return;
  878. // 1. If navigable's ongoing navigation no longer equals navigationId, then run completionSteps and return.
  879. if (navigation_id.has_value() && (!ongoing_navigation().has<String>() || ongoing_navigation().get<String>() != *navigation_id)) {
  880. completion_steps();
  881. return;
  882. }
  883. // 2. Let failure be false.
  884. auto failure = false;
  885. // 3. If navigationParams is a non-fetch scheme navigation params, then set entry's document state's document to the result of
  886. // running attempt to create a non-fetch scheme document navigationParams
  887. if (navigation_params.has<NonFetchSchemeNavigationParams>()) {
  888. // FIXME: https://github.com/whatwg/html/issues/9767
  889. // We probably are expected to skip to steps 13 and 14 and return after doing this
  890. entry->document_state->set_document(attempt_to_create_a_non_fetch_scheme_document(navigation_params.get<NonFetchSchemeNavigationParams>()));
  891. if (entry->document_state->document()) {
  892. entry->document_state->set_ever_populated(true);
  893. }
  894. completion_steps();
  895. return;
  896. }
  897. // 4. Otherwise, if navigationParams is null, then set failure to true.
  898. if (navigation_params.has<Empty>()) {
  899. failure = true;
  900. }
  901. // 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,
  902. // navigationParams's response, navigationParams's policy container's CSP list, cspNavigationType, and navigable is "Blocked", then set failure to true.
  903. // 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
  904. // navigationParams's response, navigable, and navigationParams's policy container's embedder policy is false, then set failure to true.
  905. // FIXME: 7. Otherwise, if the result of checking a navigation response's adherence to `X-Frame-Options` given navigationParams's response, navigable,
  906. // navigationParams's policy container's CSP list, and navigationParams's origin is false, then set failure to true.
  907. // 8. If failure is true, then:
  908. if (failure) {
  909. // 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.
  910. // The inline content should indicate to the user the sort of error that occurred.
  911. // FIXME: Add error message to generated error page
  912. auto error_html = load_error_page(entry->url).release_value_but_fixme_should_propagate_errors();
  913. entry->document_state->set_document(create_document_for_inline_content(this, navigation_id, error_html));
  914. // 2. Set entry's document state's document's salvageable to false.
  915. entry->document_state->document()->set_salvageable(false);
  916. // FIXME: 3. If navigationParams is not null, then:
  917. if (!navigation_params.has<Empty>()) {
  918. // 1. FIXME: Run the environment discarding steps for navigationParams's reserved environment.
  919. // 2. Invoke WebDriver BiDi navigation failed with currentBrowsingContext and a new WebDriver BiDi navigation status
  920. // whose id is navigationId, status is "canceled", and url is navigationParams's response's URL.
  921. }
  922. }
  923. // FIXME: 9. Otherwise, if navigationParams's response's status is 204 or 205, then:
  924. else if (navigation_params.get<NavigationParams>().response->status() == 204 || navigation_params.get<NavigationParams>().response->status() == 205) {
  925. // 1. Run completionSteps.
  926. completion_steps();
  927. // 2. Return.
  928. return;
  929. }
  930. // FIXME: 10. Otherwise, if navigationParams's response has a `Content-Disposition`
  931. // header specifying the attachment disposition type, then:
  932. // 11. Otherwise:
  933. else {
  934. // 1. Let document be the result of loading a document given navigationParams, sourceSnapshotParams,
  935. // and entry's document state's initiator origin.
  936. auto document = load_document(move(navigation_params.get<NavigationParams>()));
  937. // 2. If document is null, then run completionSteps and return.
  938. if (!document) {
  939. completion_steps();
  940. return;
  941. }
  942. // 3. Set entry's document state's document to document.
  943. entry->document_state->set_document(document.ptr());
  944. // 4. Set entry's document state's origin to document's origin.
  945. entry->document_state->set_origin(document->origin());
  946. }
  947. // FIXME: 12. If entry's document state's request referrer is "client", then set it to request's referrer.
  948. // https://github.com/whatwg/html/issues/9767
  949. // What is "request" here?
  950. // 13. If entry's document state's document is not null, then set entry's document state's ever populated to true.
  951. if (entry->document_state->document()) {
  952. entry->document_state->set_ever_populated(true);
  953. }
  954. // 14. Run completionSteps.
  955. completion_steps();
  956. });
  957. return {};
  958. }
  959. // To navigate a navigable navigable to a URL url using a Document sourceDocument,
  960. // with an optional POST resource, string, or null documentResource (default null),
  961. // an optional response-or-null response (default null), an optional boolean exceptionsEnabled (default false),
  962. // an optional NavigationHistoryBehavior historyHandling (default "auto"),
  963. // an optional serialized state-or-null navigationAPIState (default null),
  964. // an optional entry list or null formDataEntryList (default null),
  965. // an optional referrer policy referrerPolicy (default the empty string),
  966. // and an optional user navigation involvement userInvolvement (default "none"):
  967. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
  968. WebIDL::ExceptionOr<void> Navigable::navigate(NavigateParams params)
  969. {
  970. auto const& url = params.url;
  971. auto source_document = params.source_document;
  972. auto const& document_resource = params.document_resource;
  973. auto response = params.response;
  974. auto exceptions_enabled = params.exceptions_enabled;
  975. auto history_handling = params.history_handling;
  976. auto const& navigation_api_state = params.navigation_api_state;
  977. auto const& form_data_entry_list = params.form_data_entry_list;
  978. auto referrer_policy = params.referrer_policy;
  979. auto user_involvement = params.user_involvement;
  980. auto& active_document = *this->active_document();
  981. auto& realm = active_document.realm();
  982. auto& vm = this->vm();
  983. // 1. Let cspNavigationType be "form-submission" if formDataEntryList is non-null; otherwise "other".
  984. auto csp_navigation_type = form_data_entry_list.has_value() ? CSPNavigationType::FormSubmission : CSPNavigationType::Other;
  985. // 2. Let sourceSnapshotParams be the result of snapshotting source snapshot params given sourceDocument.
  986. auto source_snapshot_params = source_document->snapshot_source_snapshot_params();
  987. // 3. Let initiatorOriginSnapshot be sourceDocument's origin.
  988. auto initiator_origin_snapshot = source_document->origin();
  989. // 4. Let initiatorBaseURLSnapshot be sourceDocument's document base URL.
  990. auto initiator_base_url_snapshot = source_document->base_url();
  991. // 5. If sourceDocument's node navigable is not allowed by sandboxing to navigate navigable given and sourceSnapshotParams, then:
  992. if (!source_document->navigable()->allowed_by_sandboxing_to_navigate(*this, source_snapshot_params)) {
  993. // 1. If exceptionsEnabled is true, then throw a "SecurityError" DOMException.
  994. if (exceptions_enabled) {
  995. return WebIDL::SecurityError::create(realm, "Source document's node navigable is not allowed to navigate"_fly_string);
  996. }
  997. // 2 Return.
  998. return {};
  999. }
  1000. // 6. Let navigationId be the result of generating a random UUID.
  1001. String navigation_id = TRY_OR_THROW_OOM(vm, Crypto::generate_random_uuid());
  1002. // FIXME: 7. If the surrounding agent is equal to navigable's active document's relevant agent, then continue these steps.
  1003. // Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to continue these steps.
  1004. // 8. If navigable's active document's unload counter is greater than 0,
  1005. // then invoke WebDriver BiDi navigation failed with a WebDriver BiDi navigation status whose id is navigationId,
  1006. // status is "canceled", and url is url, and return.
  1007. if (active_document.unload_counter() > 0) {
  1008. // FIXME: invoke WebDriver BiDi navigation failed with a WebDriver BiDi navigation status whose id is navigationId,
  1009. // status is "canceled", and url is url
  1010. return {};
  1011. }
  1012. // 9. If historyHandling is "auto", then:
  1013. if (history_handling == Bindings::NavigationHistoryBehavior::Auto) {
  1014. // FIXME: Fix spec typo targetNavigable --> navigable
  1015. // 1. If url equals navigable's active document's URL,
  1016. // and initiatorOriginSnapshot is same origin with targetNavigable's active document's origin,
  1017. // then set historyHandling to "replace".
  1018. if (url.equals(active_document.url(), AK::URL::ExcludeFragment::Yes) && initiator_origin_snapshot.is_same_origin(active_document.origin()))
  1019. history_handling = Bindings::NavigationHistoryBehavior::Replace;
  1020. // 2. Otherwise, set historyHandling to "push".
  1021. else
  1022. history_handling = Bindings::NavigationHistoryBehavior::Push;
  1023. }
  1024. // 10. If the navigation must be a replace given url and navigable's active document, then set historyHandling to "replace".
  1025. if (navigation_must_be_a_replace(url, active_document))
  1026. history_handling = Bindings::NavigationHistoryBehavior::Replace;
  1027. // 11. If all of the following are true:
  1028. // - documentResource is null;
  1029. // - response is null;
  1030. // - url equals navigable's active session history entry's URL with exclude fragments set to true; and
  1031. // - url's fragment is non-null
  1032. if (document_resource.has<Empty>()
  1033. && !response
  1034. && url.equals(active_session_history_entry()->url, AK::URL::ExcludeFragment::Yes)
  1035. && url.fragment().has_value()) {
  1036. // 1. Navigate to a fragment given navigable, url, historyHandling, and navigationId.
  1037. TRY(navigate_to_a_fragment(url, to_history_handling_behavior(history_handling), navigation_id));
  1038. traversable_navigable()->process_session_history_traversal_queue();
  1039. // 2. Return.
  1040. return {};
  1041. }
  1042. // 12. If navigable's parent is non-null, then set navigable's is delaying load events to true.
  1043. if (parent() != nullptr)
  1044. set_delaying_load_events(true);
  1045. // 13. Let targetBrowsingContext be navigable's active browsing context.
  1046. [[maybe_unused]] auto target_browsing_context = active_browsing_context();
  1047. // 14. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
  1048. auto target_snapshot_params = snapshot_target_snapshot_params();
  1049. // 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".
  1050. // 16. If navigable's ongoing navigation is "traversal", then:
  1051. if (ongoing_navigation().has<Traversal>()) {
  1052. // 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.
  1053. // 2. Return.
  1054. return {};
  1055. }
  1056. // 17. Set navigable's ongoing navigation to navigationId.
  1057. set_ongoing_navigation(navigation_id);
  1058. // 18. If url's scheme is "javascript", then:
  1059. if (url.scheme() == "javascript"sv) {
  1060. // 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.
  1061. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this, url, history_handling, initiator_origin_snapshot, csp_navigation_type, navigation_id] {
  1062. (void)navigate_to_a_javascript_url(url, to_history_handling_behavior(history_handling), initiator_origin_snapshot, csp_navigation_type, navigation_id);
  1063. });
  1064. // 2. Return.
  1065. return {};
  1066. }
  1067. // 19. If all of the following are true:
  1068. // - userInvolvement is not "browser UI";
  1069. // - navigable's active document's origin is same origin-domain with sourceDocument's origin;
  1070. // - navigable's active document's is initial about:blank is false; and
  1071. // - url's scheme is a fetch scheme
  1072. // then:
  1073. if (user_involvement != UserNavigationInvolvement::BrowserUI && active_document.origin().is_same_origin_domain(source_document->origin()) && !active_document.is_initial_about_blank() && Fetch::Infrastructure::is_fetch_scheme(url.scheme())) {
  1074. // 1. Let navigation be navigable's active window's navigation API.
  1075. auto navigation = active_window()->navigation();
  1076. // 2. Let entryListForFiring be formDataEntryList if documentResource is a POST resource; otherwise, null.
  1077. auto entry_list_for_firing = [&]() -> Optional<Vector<XHR::FormDataEntry>&> {
  1078. if (document_resource.has<POSTResource>())
  1079. return form_data_entry_list;
  1080. return {};
  1081. }();
  1082. // 3. Let navigationAPIStateForFiring be navigationAPIState if navigationAPIState is not null;
  1083. // otherwise, StructuredSerializeForStorage(undefined).
  1084. auto navigation_api_state_for_firing = navigation_api_state.value_or(MUST(structured_serialize_for_storage(vm, JS::js_undefined())));
  1085. // FIXME: 4. Let continue be the result of firing a push/replace/reload navigate event at navigation
  1086. // with navigationType set to historyHandling, isSameDocument set to false, userInvolvement set to userInvolvement,
  1087. // formDataEntryList set to entryListForFiring, destinationURL set to url, and navigationAPIState set to navigationAPIStateForFiring.
  1088. (void)navigation;
  1089. (void)entry_list_for_firing;
  1090. (void)navigation_api_state_for_firing;
  1091. // FIXME: 5. If continue is false, then return.
  1092. }
  1093. if (is_top_level_traversable()) {
  1094. if (auto* page = active_browsing_context()->page())
  1095. page->client().page_did_start_loading(url, false);
  1096. }
  1097. // 20. In parallel, run these steps:
  1098. Platform::EventLoopPlugin::the().deferred_invoke([this, source_snapshot_params, target_snapshot_params, csp_navigation_type, document_resource, url, navigation_id, referrer_policy, initiator_origin_snapshot, response, history_handling, initiator_base_url_snapshot] {
  1099. // NOTE: Not in the spec but subsequent steps will fail because destroyed navigable does not have active document.
  1100. if (has_been_destroyed())
  1101. return;
  1102. // FIXME: 1. Let unloadPromptCanceled be the result of checking if unloading is user-canceled for navigable's active document's inclusive descendant navigables.
  1103. // FIXME: 2. If unloadPromptCanceled is true, or navigable's ongoing navigation is no longer navigationId, then:
  1104. if (!ongoing_navigation().has<String>() || ongoing_navigation().get<String>() != navigation_id) {
  1105. // 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.
  1106. // 2. Abort these steps.
  1107. return;
  1108. }
  1109. // 3. Queue a global task on the navigation and traversal task source given navigable's active window to abort navigable's active document.
  1110. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this] {
  1111. VERIFY(this->active_document());
  1112. this->active_document()->abort();
  1113. });
  1114. // 4. Let documentState be a new document state with
  1115. // request referrer policy: referrerPolicy
  1116. // initiator origin: initiatorOriginSnapshot
  1117. // resource: documentResource
  1118. // navigable target name: navigable's target name
  1119. JS::NonnullGCPtr<DocumentState> document_state = *heap().allocate_without_realm<DocumentState>();
  1120. document_state->set_request_referrer_policy(referrer_policy);
  1121. document_state->set_initiator_origin(initiator_origin_snapshot);
  1122. document_state->set_resource(document_resource);
  1123. document_state->set_navigable_target_name(target_name());
  1124. // 5. If url matches about:blank or is about:srcdoc, then set documentState's origin to documentState's initiator origin.
  1125. // FIXME: should this say "matches about:srcdoc"
  1126. if (url_matches_about_blank(url) || url == "about:srcdoc"sv) {
  1127. // 1. Set documentState's origin to initiatorOriginSnapshot.
  1128. document_state->set_origin(document_state->initiator_origin());
  1129. // 2. Set documentState's about base URL to initiatorBaseURLSnapshot.
  1130. document_state->set_about_base_url(initiator_base_url_snapshot);
  1131. }
  1132. // 6. Let historyEntry be a new session history entry, with its URL set to url and its document state set to documentState.
  1133. JS::NonnullGCPtr<SessionHistoryEntry> history_entry = *heap().allocate_without_realm<SessionHistoryEntry>();
  1134. history_entry->url = url;
  1135. history_entry->document_state = document_state;
  1136. // 8. Let navigationParams be null.
  1137. Variant<Empty, NavigationParams, NonFetchSchemeNavigationParams> navigation_params = Empty {};
  1138. // FIXME: 9. If response is non-null:
  1139. if (response) {
  1140. }
  1141. // 10. Attempt to populate the history entry's document
  1142. // for historyEntry, given navigable, "navigate", sourceSnapshotParams,
  1143. // targetSnapshotParams, navigationId, navigationParams, cspNavigationType, with allowPOST
  1144. // set to true and completionSteps set to the following step:
  1145. populate_session_history_entry_document(history_entry, source_snapshot_params, target_snapshot_params, navigation_id, move(navigation_params), csp_navigation_type, true, [this, history_entry, history_handling, navigation_id] {
  1146. // 1. Append session history traversal steps to navigable's traversable to finalize a cross-document navigation given navigable, historyHandling, and historyEntry.
  1147. traversable_navigable()->append_session_history_traversal_steps([this, history_entry, history_handling, navigation_id] {
  1148. if (this->has_been_destroyed()) {
  1149. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  1150. return;
  1151. }
  1152. if (this->ongoing_navigation() != navigation_id) {
  1153. // NOTE: This check is not in the spec but we should not continue navigation if ongoing navigation id has changed.
  1154. return;
  1155. }
  1156. finalize_a_cross_document_navigation(*this, to_history_handling_behavior(history_handling), history_entry);
  1157. });
  1158. }).release_value_but_fixme_should_propagate_errors();
  1159. });
  1160. return {};
  1161. }
  1162. WebIDL::ExceptionOr<void> Navigable::navigate_to_a_fragment(AK::URL const& url, HistoryHandlingBehavior history_handling, String)
  1163. {
  1164. // FIXME: 1. Let navigation be navigable's active window's navigation API.
  1165. // FIXME: 2. Let destinationNavigationAPIState be navigable's active session history entry's navigation API state.
  1166. // FIXME: 3. If navigationAPIState is not null, then set destinationNavigationAPIState to navigationAPIState.
  1167. // 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,
  1168. // userInvolvement set to userInvolvement, and destinationURL set to url, and navigationAPIState set to destinationNavigationAPIState.
  1169. // FIXME: 5. If continue is false, then return.
  1170. // 6. Let historyEntry be a new session history entry, with
  1171. // URL: url
  1172. // document state: navigable's active session history entry's document state
  1173. // navigation API state: destinationNavigationAPIState
  1174. // scroll restoration mode: navigable's active session history entry's scroll restoration mode
  1175. JS::NonnullGCPtr<SessionHistoryEntry> history_entry = heap().allocate_without_realm<SessionHistoryEntry>();
  1176. history_entry->url = url;
  1177. history_entry->document_state = active_session_history_entry()->document_state;
  1178. history_entry->scroll_restoration_mode = active_session_history_entry()->scroll_restoration_mode;
  1179. // 7. Let entryToReplace be navigable's active session history entry if historyHandling is "replace", otherwise null.
  1180. auto entry_to_replace = history_handling == HistoryHandlingBehavior::Replace ? active_session_history_entry() : nullptr;
  1181. // 8. Let history be navigable's active document's history object.
  1182. auto history = active_document()->history();
  1183. // 9. Let scriptHistoryIndex be history's index.
  1184. auto script_history_index = history->m_index;
  1185. // 10. Let scriptHistoryLength be history's length.
  1186. auto script_history_length = history->m_length;
  1187. // 11. If historyHandling is "push", then:
  1188. if (history_handling == HistoryHandlingBehavior::Push) {
  1189. // FIXME: 1. Set history's state to null.
  1190. // 2. Increment scriptHistoryIndex.
  1191. script_history_index++;
  1192. // 3. Set scriptHistoryLength to scriptHistoryIndex + 1.
  1193. script_history_length = script_history_index + 1;
  1194. }
  1195. // 12. Set navigable's active session history entry to historyEntry.
  1196. m_active_session_history_entry = history_entry;
  1197. // 13. Update document for history step application given navigable's active document, historyEntry, true, scriptHistoryIndex, and scriptHistoryLength.
  1198. active_document()->update_for_history_step_application(*history_entry, true, script_history_length, script_history_index);
  1199. // FIXME: 14. Update the navigation API entries for a same-document navigation given navigation, historyEntry, and historyHandling.
  1200. // 15. Scroll to the fragment given navigable's active document.
  1201. // FIXME: Specification doesn't say when document url needs to update during fragment navigation
  1202. active_document()->set_url(url);
  1203. active_document()->scroll_to_the_fragment();
  1204. // 16. Let traversable be navigable's traversable navigable.
  1205. auto traversable = traversable_navigable();
  1206. // 17. Append the following session history synchronous navigation steps involving navigable to traversable:
  1207. traversable->append_session_history_traversal_steps([this, traversable, history_entry, entry_to_replace] {
  1208. // 1. Finalize a same-document navigation given traversable, navigable, historyEntry, and entryToReplace.
  1209. finalize_a_same_document_navigation(*traversable, *this, history_entry, entry_to_replace);
  1210. // FIXME: 2. Invoke WebDriver BiDi fragment navigated with navigable's active browsing context and a new WebDriver BiDi
  1211. // navigation status whose id is navigationId, url is url, and status is "complete".
  1212. });
  1213. return {};
  1214. }
  1215. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#evaluate-a-javascript:-url
  1216. WebIDL::ExceptionOr<JS::GCPtr<DOM::Document>> Navigable::evaluate_javascript_url(AK::URL const& url, Origin const& new_document_origin, String navigation_id)
  1217. {
  1218. auto& vm = this->vm();
  1219. auto& realm = active_window()->realm();
  1220. // 1. Let urlString be the result of running the URL serializer on url.
  1221. auto url_string = url.serialize();
  1222. // 2. Let encodedScriptSource be the result of removing the leading "javascript:" from urlString.
  1223. auto encoded_script_source = url_string.substring_view(11, url_string.length() - 11);
  1224. // 3. Let scriptSource be the UTF-8 decoding of the percent-decoding of encodedScriptSource.
  1225. auto script_source = AK::URL::percent_decode(encoded_script_source);
  1226. // 4. Let settings be targetNavigable's active document's relevant settings object.
  1227. auto& settings = active_document()->relevant_settings_object();
  1228. // 5. Let baseURL be settings's API base URL.
  1229. auto base_url = settings.api_base_url();
  1230. // 6. Let script be the result of creating a classic script given scriptSource, settings, baseURL, and the default classic script fetch options.
  1231. auto script = HTML::ClassicScript::create("(javascript url)", script_source, settings, base_url);
  1232. // 7. Let evaluationStatus be the result of running the classic script script.
  1233. auto evaluation_status = script->run();
  1234. // 8. Let result be null.
  1235. String result;
  1236. // 9. If evaluationStatus is a normal completion, and evaluationStatus.[[Value]] is a String, then set result to evaluationStatus.[[Value]].
  1237. if (evaluation_status.type() == JS::Completion::Type::Normal && evaluation_status.value()->is_string()) {
  1238. result = evaluation_status.value()->as_string().utf8_string();
  1239. } else {
  1240. // 10. Otherwise, return null.
  1241. return nullptr;
  1242. }
  1243. // 11. Let response be a new response with
  1244. // URL: targetNavigable's active document's URL
  1245. // header list: «(`Content-Type`, `text/html;charset=utf-8`)»
  1246. // body: the UTF-8 encoding of result, as a body
  1247. auto response = Fetch::Infrastructure::Response::create(vm);
  1248. response->url_list().append(active_document()->url());
  1249. auto header = TRY_OR_THROW_OOM(vm, Fetch::Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html"sv));
  1250. TRY_OR_THROW_OOM(vm, response->header_list()->append(move(header)));
  1251. response->set_body(TRY(Fetch::Infrastructure::byte_sequence_as_body(realm, result.bytes())));
  1252. // 12. Let policyContainer be targetNavigable's active document's policy container.
  1253. auto const& policy_container = active_document()->policy_container();
  1254. // FIXME: 13. Let finalSandboxFlags be policyContainer's CSP list's CSP-derived sandboxing flags.
  1255. auto final_sandbox_flags = SandboxingFlagSet {};
  1256. // 14. Let coop be targetNavigable's active document's cross-origin opener policy.
  1257. auto const& coop = active_document()->cross_origin_opener_policy();
  1258. // 15. Let coopEnforcementResult be a new cross-origin opener policy enforcement result with
  1259. // url: url
  1260. // origin: newDocumentOrigin
  1261. // cross-origin opener policy: coop
  1262. CrossOriginOpenerPolicyEnforcementResult coop_enforcement_result {
  1263. .url = url,
  1264. .origin = new_document_origin,
  1265. .cross_origin_opener_policy = coop,
  1266. };
  1267. // 16. Let navigationParams be a new navigation params, with
  1268. // id: navigationId
  1269. // navigable: targetNavigable
  1270. // request: null
  1271. // response: response
  1272. // fetch controller: null
  1273. // commit early hints: null
  1274. // COOP enforcement result: coopEnforcementResult
  1275. // reserved environment: null
  1276. // origin: newDocumentOrigin
  1277. // policy container: policyContainer
  1278. // final sandboxing flag set: finalSandboxFlags
  1279. // cross-origin opener policy: coop
  1280. // FIXME: navigation timing type: "navigate"
  1281. // about base URL: targetNavigable's active document's about base URL
  1282. NavigationParams navigation_params {
  1283. .id = navigation_id,
  1284. .navigable = this,
  1285. .request = {},
  1286. .response = response,
  1287. .fetch_controller = nullptr,
  1288. .commit_early_hints = nullptr,
  1289. .coop_enforcement_result = move(coop_enforcement_result),
  1290. .reserved_environment = {},
  1291. .origin = new_document_origin,
  1292. .policy_container = policy_container,
  1293. .final_sandboxing_flag_set = final_sandbox_flags,
  1294. .cross_origin_opener_policy = coop,
  1295. .about_base_url = active_document()->about_base_url(),
  1296. };
  1297. // 17. Return the result of loading an HTML document given navigationParams.
  1298. return load_document(move(navigation_params));
  1299. }
  1300. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate-to-a-javascript:-url
  1301. 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)
  1302. {
  1303. // 1. Assert: historyHandling is "replace".
  1304. VERIFY(history_handling == HistoryHandlingBehavior::Replace);
  1305. // 2. Set the ongoing navigation for targetNavigable to null.
  1306. set_ongoing_navigation({});
  1307. // 3. If initiatorOrigin is not same origin-domain with targetNavigable's active document's origin, then return.
  1308. if (!initiator_origin.is_same_origin_domain(active_document()->origin()))
  1309. return {};
  1310. // FIXME: 4. Let request be a new request whose URL is url.
  1311. // 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.
  1312. (void)csp_navigation_type;
  1313. // 6. Let newDocument be the result of evaluating a javascript: URL given targetNavigable, url, and initiatorOrigin.
  1314. auto new_document = TRY(evaluate_javascript_url(url, initiator_origin, navigation_id));
  1315. // 7. If newDocument is null, then return.
  1316. if (!new_document) {
  1317. // NOTE: In this case, some JavaScript code was executed, but no new Document was created, so we will not perform a navigation.
  1318. return {};
  1319. }
  1320. // 8. Assert: initiatorOrigin is newDocument's origin.
  1321. VERIFY(initiator_origin == new_document->origin());
  1322. // 9. Let entryToReplace be targetNavigable's active session history entry.
  1323. auto entry_to_replace = active_session_history_entry();
  1324. // 10. Let oldDocState be entryToReplace's document state.
  1325. auto old_doc_state = entry_to_replace->document_state;
  1326. // 11. Let documentState be a new document state with
  1327. // document: newDocument
  1328. // history policy container: a clone of the oldDocState's history policy container if it is non-null; null otherwise
  1329. // request referrer: oldDocState's request referrer
  1330. // request referrer policy: oldDocState's request referrer policy
  1331. // initiator origin: initiatorOrigin
  1332. // origin: initiatorOrigin
  1333. // about base URL: oldDocState's about base URL
  1334. // resource: null
  1335. // ever populated: true
  1336. // navigable target name: oldDocState's navigable target name
  1337. JS::NonnullGCPtr<DocumentState> document_state = *heap().allocate_without_realm<DocumentState>();
  1338. document_state->set_document(new_document);
  1339. document_state->set_history_policy_container(old_doc_state->history_policy_container());
  1340. document_state->set_request_referrer(old_doc_state->request_referrer());
  1341. document_state->set_request_referrer_policy(old_doc_state->request_referrer_policy());
  1342. document_state->set_initiator_origin(initiator_origin);
  1343. document_state->set_origin(initiator_origin);
  1344. document_state->set_about_base_url(old_doc_state->about_base_url());
  1345. document_state->set_ever_populated(true);
  1346. document_state->set_navigable_target_name(old_doc_state->navigable_target_name());
  1347. // 12. Let historyEntry be a new session history entry, with
  1348. // URL: entryToReplace's URL
  1349. // document state: documentState
  1350. JS::NonnullGCPtr<SessionHistoryEntry> history_entry = *heap().allocate_without_realm<SessionHistoryEntry>();
  1351. history_entry->url = entry_to_replace->url;
  1352. history_entry->document_state = document_state;
  1353. // 13. Append session history traversal steps to targetNavigable's traversable to finalize a cross-document navigation with targetNavigable, historyHandling, and historyEntry.
  1354. traversable_navigable()->append_session_history_traversal_steps([this, history_entry, history_handling, navigation_id] {
  1355. finalize_a_cross_document_navigation(*this, history_handling, history_entry);
  1356. });
  1357. return {};
  1358. }
  1359. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#reload
  1360. void Navigable::reload()
  1361. {
  1362. // 1. Set navigable's active session history entry's document state's reload pending to true.
  1363. active_session_history_entry()->document_state->set_reload_pending(true);
  1364. // 2. Let traversable be navigable's traversable navigable.
  1365. auto traversable = traversable_navigable();
  1366. // 3. Append the following session history traversal steps to traversable:
  1367. traversable->append_session_history_traversal_steps([traversable] {
  1368. // 1. Apply the reload history step to traversable.
  1369. traversable->apply_the_reload_history_step();
  1370. });
  1371. }
  1372. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#the-navigation-must-be-a-replace
  1373. bool navigation_must_be_a_replace(AK::URL const& url, DOM::Document const& document)
  1374. {
  1375. return url.scheme() == "javascript"sv || document.is_initial_about_blank();
  1376. }
  1377. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#allowed-to-navigate
  1378. bool Navigable::allowed_by_sandboxing_to_navigate(Navigable const& target, SourceSnapshotParams const& source_snapshot_params)
  1379. {
  1380. auto& source = *this;
  1381. auto is_ancestor_of = [](Navigable const& a, Navigable const& b) {
  1382. for (auto parent = b.parent(); parent; parent = parent->parent()) {
  1383. if (parent.ptr() == &a)
  1384. return true;
  1385. }
  1386. return false;
  1387. };
  1388. // A navigable source is allowed by sandboxing to navigate a second navigable target,
  1389. // given a source snapshot params sourceSnapshotParams, if the following steps return true:
  1390. // 1. If source is target, then return true.
  1391. if (&source == &target)
  1392. return true;
  1393. // 2. If source is an ancestor of target, then return true.
  1394. if (is_ancestor_of(source, target))
  1395. return true;
  1396. // 3. If target is an ancestor of source, then:
  1397. if (is_ancestor_of(target, source)) {
  1398. // 1. If target is not a top-level traversable, then return true.
  1399. if (!target.is_top_level_traversable())
  1400. return true;
  1401. // 2. If sourceSnapshotParams's has transient activation is true, and sourceSnapshotParams's sandboxing flags's
  1402. // sandboxed top-level navigation with user activation browsing context flag is set, then return false.
  1403. if (source_snapshot_params.has_transient_activation && has_flag(source_snapshot_params.sandboxing_flags, SandboxingFlagSet::SandboxedTopLevelNavigationWithUserActivation))
  1404. return false;
  1405. // 3. If sourceSnapshotParams's has transient activation is false, and sourceSnapshotParams's sandboxing flags's
  1406. // sandboxed top-level navigation without user activation browsing context flag is set, then return false.
  1407. if (!source_snapshot_params.has_transient_activation && has_flag(source_snapshot_params.sandboxing_flags, SandboxingFlagSet::SandboxedTopLevelNavigationWithoutUserActivation))
  1408. return false;
  1409. // 4. Return true.
  1410. return true;
  1411. }
  1412. // 4. If target is a top-level traversable:
  1413. if (target.is_top_level_traversable()) {
  1414. // FIXME: 1. If source is the one permitted sandboxed navigator of target, then return true.
  1415. // 2. If sourceSnapshotParams's sandboxing flags's sandboxed navigation browsing context flag is set, then return false.
  1416. if (has_flag(source_snapshot_params.sandboxing_flags, SandboxingFlagSet::SandboxedNavigation))
  1417. return false;
  1418. // 3. Return true.
  1419. return true;
  1420. }
  1421. // 5. If sourceSnapshotParams's sandboxing flags's sandboxed navigation browsing context flag is set, then return false.
  1422. // 6. Return true.
  1423. return !has_flag(source_snapshot_params.sandboxing_flags, SandboxingFlagSet::SandboxedNavigation);
  1424. }
  1425. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#snapshotting-target-snapshot-params
  1426. TargetSnapshotParams Navigable::snapshot_target_snapshot_params()
  1427. {
  1428. // To snapshot target snapshot params given a navigable targetNavigable, return a new target snapshot params
  1429. // with sandboxing flags set to the result of determining the creation sandboxing flags given targetNavigable's
  1430. // active browsing context and targetNavigable's container.
  1431. return { determine_the_creation_sandboxing_flags(*active_browsing_context(), container()) };
  1432. }
  1433. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#finalize-a-cross-document-navigation
  1434. void finalize_a_cross_document_navigation(JS::NonnullGCPtr<Navigable> navigable, HistoryHandlingBehavior history_handling, JS::NonnullGCPtr<SessionHistoryEntry> history_entry)
  1435. {
  1436. // NOTE: This is not in the spec but we should not navigate destroyed navigable.
  1437. if (navigable->has_been_destroyed())
  1438. return;
  1439. // 1. FIXME: Assert: this is running on navigable's traversable navigable's session history traversal queue.
  1440. // 2. Set navigable's is delaying load events to false.
  1441. navigable->set_delaying_load_events(false);
  1442. // 3. If historyEntry's document is null, then return.
  1443. if (!history_entry->document_state->document())
  1444. return;
  1445. // 4. If all of the following are true:
  1446. // - navigable's parent is null;
  1447. // - historyEntry's document's browsing context is not an auxiliary browsing context whose opener browsing context is non-null; and
  1448. // - historyEntry's document's origin is not navigable's active document's origin
  1449. // then set historyEntry's document state's navigable target name to the empty string.
  1450. 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())
  1451. history_entry->document_state->set_navigable_target_name(String {});
  1452. // 5. Let entryToReplace be navigable's active session history entry if historyHandling is "replace", otherwise null.
  1453. auto entry_to_replace = history_handling == HistoryHandlingBehavior::Replace ? navigable->active_session_history_entry() : nullptr;
  1454. // 6. Let traversable be navigable's traversable navigable.
  1455. auto traversable = navigable->traversable_navigable();
  1456. // 7. Let targetStep be null.
  1457. int target_step;
  1458. // 8. Let targetEntries be the result of getting session history entries for navigable.
  1459. auto& target_entries = navigable->get_session_history_entries();
  1460. // 9. If entryToReplace is null, then:
  1461. if (entry_to_replace == nullptr) {
  1462. // 1. Clear the forward session history of traversable.
  1463. traversable->clear_the_forward_session_history();
  1464. // 2. Set targetStep to traversable's current session history step + 1.
  1465. target_step = traversable->current_session_history_step() + 1;
  1466. // 3. Set historyEntry's step to targetStep.
  1467. history_entry->step = target_step;
  1468. // 4. Append historyEntry to targetEntries.
  1469. target_entries.append(history_entry);
  1470. } else {
  1471. // 1. Replace entryToReplace with historyEntry in targetEntries.
  1472. *(target_entries.find(*entry_to_replace)) = history_entry;
  1473. // 2. Set historyEntry's step to entryToReplace's step.
  1474. history_entry->step = entry_to_replace->step;
  1475. // 3. If historyEntry's document state's origin is same origin with entryToReplace's document state's origin,
  1476. // then set historyEntry's navigation API key to entryToReplace's navigation API key.
  1477. 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())) {
  1478. history_entry->navigation_api_key = entry_to_replace->navigation_api_key;
  1479. }
  1480. // 4. Set targetStep to traversable's current session history step.
  1481. target_step = traversable->current_session_history_step();
  1482. }
  1483. // 10. Apply the push/replace history step targetStep to traversable.
  1484. traversable->apply_the_push_or_replace_history_step(target_step);
  1485. }
  1486. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#url-and-history-update-steps
  1487. void perform_url_and_history_update_steps(DOM::Document& document, AK::URL new_url, HistoryHandlingBehavior history_handling)
  1488. {
  1489. // 1. Let navigable be document's node navigable.
  1490. auto navigable = document.navigable();
  1491. // 2. Let activeEntry be navigable's active session history entry.
  1492. auto active_entry = navigable->active_session_history_entry();
  1493. // 3. Let newEntry be a new session history entry, with
  1494. // URL: newURL
  1495. // serialized state: if serializedData is not null, serializedData; otherwise activeEntry's classic history API state
  1496. // document state: activeEntry's document state
  1497. // scroll restoration mode: activeEntry's scroll restoration mode
  1498. // persisted user state: activeEntry's persisted user state
  1499. JS::NonnullGCPtr<SessionHistoryEntry> new_entry = document.heap().allocate_without_realm<SessionHistoryEntry>();
  1500. new_entry->url = new_url;
  1501. new_entry->document_state = active_entry->document_state;
  1502. new_entry->scroll_restoration_mode = active_entry->scroll_restoration_mode;
  1503. // 4. If document's is initial about:blank is true, then set historyHandling to "replace".
  1504. if (document.is_initial_about_blank()) {
  1505. history_handling = HistoryHandlingBehavior::Replace;
  1506. }
  1507. // 5. Let entryToReplace be activeEntry if historyHandling is "replace", otherwise null.
  1508. auto entry_to_replace = history_handling == HistoryHandlingBehavior::Replace ? active_entry : nullptr;
  1509. // 6. If historyHandling is "push", then:
  1510. if (history_handling == HistoryHandlingBehavior::Push) {
  1511. // 1. Increment document's history object's index.
  1512. document.history()->m_index++;
  1513. // 2. Set document's history object's length to its index + 1.
  1514. document.history()->m_length = document.history()->m_index + 1;
  1515. }
  1516. // FIXME: 7. If serializedData is not null, then restore the history object state given document and newEntry.
  1517. // 8. Set document's URL to newURL.
  1518. document.set_url(new_url);
  1519. // FIXME: 9. Set document's latest entry to newEntry.
  1520. // 10. Set navigable's active session history entry to newEntry.
  1521. navigable->set_active_session_history_entry(new_entry);
  1522. // FIXME: 11. Update the navigation API entries for a same-document navigation given document's relevant global object's navigation API, newEntry, and historyHandling.
  1523. // 12. Let traversable be navigable's traversable navigable.
  1524. auto traversable = navigable->traversable_navigable();
  1525. // 13. Append the following session history synchronous navigation steps involving navigable to traversable:
  1526. traversable->append_session_history_traversal_steps([traversable, navigable, new_entry, entry_to_replace] {
  1527. // 1. Finalize a same-document navigation given traversable, navigable, newEntry, and entryToReplace.
  1528. finalize_a_same_document_navigation(*traversable, *navigable, new_entry, entry_to_replace);
  1529. });
  1530. }
  1531. void Navigable::scroll_offset_did_change()
  1532. {
  1533. // https://w3c.github.io/csswg-drafts/cssom-view-1/#scrolling-events
  1534. // Whenever a viewport gets scrolled (whether in response to user interaction or by an API), the user agent must run these steps:
  1535. // 1. Let doc be the viewport’s associated Document.
  1536. auto doc = active_document();
  1537. VERIFY(doc);
  1538. // 2. If doc is already in doc’s pending scroll event targets, abort these steps.
  1539. for (auto& target : doc->pending_scroll_event_targets()) {
  1540. if (target.ptr() == doc)
  1541. return;
  1542. }
  1543. // 3. Append doc to doc’s pending scroll event targets.
  1544. doc->pending_scroll_event_targets().append(*doc);
  1545. }
  1546. CSSPixelRect Navigable::to_top_level_rect(CSSPixelRect const& a_rect)
  1547. {
  1548. auto rect = a_rect;
  1549. rect.set_location(to_top_level_position(a_rect.location()));
  1550. return rect;
  1551. }
  1552. CSSPixelPoint Navigable::to_top_level_position(CSSPixelPoint a_position)
  1553. {
  1554. auto position = a_position;
  1555. for (auto ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  1556. if (is<TraversableNavigable>(*ancestor))
  1557. break;
  1558. if (!ancestor->container())
  1559. return {};
  1560. if (!ancestor->container()->layout_node())
  1561. return {};
  1562. position.translate_by(ancestor->container()->layout_node()->box_type_agnostic_position());
  1563. }
  1564. return position;
  1565. }
  1566. void Navigable::set_viewport_rect(CSSPixelRect const& rect)
  1567. {
  1568. bool did_change = false;
  1569. if (m_size != rect.size()) {
  1570. m_size = rect.size();
  1571. if (auto document = active_document()) {
  1572. // NOTE: Resizing the viewport changes the reference value for viewport-relative CSS lengths.
  1573. document->invalidate_style();
  1574. document->set_needs_layout();
  1575. }
  1576. did_change = true;
  1577. }
  1578. if (m_viewport_scroll_offset != rect.location()) {
  1579. m_viewport_scroll_offset = rect.location();
  1580. scroll_offset_did_change();
  1581. did_change = true;
  1582. }
  1583. if (did_change && active_document()) {
  1584. active_document()->inform_all_viewport_clients_about_the_current_viewport_rect();
  1585. }
  1586. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  1587. HTML::main_thread_event_loop().schedule();
  1588. }
  1589. void Navigable::set_size(CSSPixelSize size)
  1590. {
  1591. if (m_size == size)
  1592. return;
  1593. m_size = size;
  1594. if (auto document = active_document()) {
  1595. document->invalidate_style();
  1596. document->set_needs_layout();
  1597. }
  1598. if (auto document = active_document()) {
  1599. document->inform_all_viewport_clients_about_the_current_viewport_rect();
  1600. }
  1601. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  1602. HTML::main_thread_event_loop().schedule();
  1603. }
  1604. void Navigable::set_needs_display()
  1605. {
  1606. set_needs_display(viewport_rect());
  1607. }
  1608. void Navigable::set_needs_display(CSSPixelRect const& rect)
  1609. {
  1610. if (!viewport_rect().intersects(rect))
  1611. return;
  1612. if (is<TraversableNavigable>(*this)) {
  1613. static_cast<TraversableNavigable*>(this)->page()->client().page_did_invalidate(to_top_level_rect(rect));
  1614. return;
  1615. }
  1616. if (container() && container()->layout_node())
  1617. container()->layout_node()->set_needs_display();
  1618. }
  1619. // https://html.spec.whatwg.org/#rendering-opportunity
  1620. bool Navigable::has_a_rendering_opportunity() const
  1621. {
  1622. // A navigable has a rendering opportunity if the user agent is currently able to present
  1623. // the contents of the navigable to the user,
  1624. // accounting for hardware refresh rate constraints and user agent throttling for performance reasons,
  1625. // but considering content presentable even if it's outside the viewport.
  1626. // A navigable has no rendering opportunities if its active document is render-blocked
  1627. // or if it is suppressed for view transitions;
  1628. // otherwise, rendering opportunities are determined based on hardware constraints
  1629. // such as display refresh rates and other factors such as page performance
  1630. // or whether the document's visibility state is "visible".
  1631. // Rendering opportunities typically occur at regular intervals.
  1632. // FIXME: We should at the very least say `false` here if we're an inactive browser tab.
  1633. return true;
  1634. }
  1635. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#inform-the-navigation-api-about-aborting-navigation
  1636. void Navigable::inform_the_navigation_api_about_aborting_navigation()
  1637. {
  1638. // FIXME: 1. If this algorithm is running on navigable's active window's relevant agent's event loop, then continue on to the following steps.
  1639. // Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to run the following steps.
  1640. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [this] {
  1641. // 2. Let navigation be navigable's active window's navigation API.
  1642. auto navigation = active_window()->navigation();
  1643. // 3. If navigation's ongoing navigate event is null, then return.
  1644. if (navigation->ongoing_navigate_event() == nullptr)
  1645. return;
  1646. // 4. Abort the ongoing navigation given navigation.
  1647. navigation->abort_the_ongoing_navigation();
  1648. });
  1649. }
  1650. }