Navigable.cpp 94 KB

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