Navigable.cpp 104 KB

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