Navigable.cpp 112 KB

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