Navigable.cpp 99 KB

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