Navigable.cpp 94 KB

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