Navigable.cpp 102 KB

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