Navigable.cpp 108 KB

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