Navigable.cpp 110 KB

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