Navigable.cpp 107 KB

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