Navigable.cpp 111 KB

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