Navigable.cpp 100 KB

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