BrowsingContext.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/Bindings/MainThreadVM.h>
  7. #include <LibWeb/DOM/Document.h>
  8. #include <LibWeb/DOM/ElementFactory.h>
  9. #include <LibWeb/DOM/Event.h>
  10. #include <LibWeb/DOM/HTMLCollection.h>
  11. #include <LibWeb/DOM/Range.h>
  12. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  13. #include <LibWeb/HTML/BrowsingContext.h>
  14. #include <LibWeb/HTML/BrowsingContextGroup.h>
  15. #include <LibWeb/HTML/CrossOrigin/CrossOriginOpenerPolicy.h>
  16. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  17. #include <LibWeb/HTML/HTMLAnchorElement.h>
  18. #include <LibWeb/HTML/HTMLDocument.h>
  19. #include <LibWeb/HTML/HTMLInputElement.h>
  20. #include <LibWeb/HTML/NavigableContainer.h>
  21. #include <LibWeb/HTML/RemoteBrowsingContext.h>
  22. #include <LibWeb/HTML/SandboxingFlagSet.h>
  23. #include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
  24. #include <LibWeb/HTML/TraversableNavigable.h>
  25. #include <LibWeb/HTML/Window.h>
  26. #include <LibWeb/HTML/WindowProxy.h>
  27. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  28. #include <LibWeb/Infra/Strings.h>
  29. #include <LibWeb/Layout/BreakNode.h>
  30. #include <LibWeb/Layout/TextNode.h>
  31. #include <LibWeb/Layout/Viewport.h>
  32. #include <LibWeb/Namespace.h>
  33. #include <LibWeb/Page/Page.h>
  34. #include <LibWeb/URL/URL.h>
  35. namespace Web::HTML {
  36. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#matches-about:blank
  37. static bool url_matches_about_blank(AK::URL const& url)
  38. {
  39. // A URL matches about:blank if its scheme is "about", its path contains a single string "blank", its username and password are the empty string, and its host is null.
  40. return url.scheme() == "about"sv
  41. && url.serialize_path() == "blank"sv
  42. && url.username().is_empty()
  43. && url.password().is_empty()
  44. && url.host().has<Empty>();
  45. }
  46. // FIXME: This is an outdated older version of "determining the origin" and should be removed.
  47. // https://html.spec.whatwg.org/multipage/browsers.html#determining-the-origin
  48. HTML::Origin determine_the_origin(BrowsingContext const& browsing_context, Optional<AK::URL> url, SandboxingFlagSet sandbox_flags, Optional<HTML::Origin> invocation_origin)
  49. {
  50. // 1. If sandboxFlags has its sandboxed origin browsing context flag set, then return a new opaque origin.
  51. if (sandbox_flags.flags & SandboxingFlagSet::SandboxedOrigin) {
  52. return HTML::Origin {};
  53. }
  54. // 2. If url is null, then return a new opaque origin.
  55. if (!url.has_value()) {
  56. return HTML::Origin {};
  57. }
  58. // 3. If invocationOrigin is non-null and url matches about:blank, then return invocationOrigin.
  59. if (invocation_origin.has_value() && url_matches_about_blank(*url)) {
  60. return invocation_origin.value();
  61. }
  62. // 4. If url is about:srcdoc, then return the origin of browsingContext's container document.
  63. if (url == AK::URL("about:srcdoc")) {
  64. VERIFY(browsing_context.container_document());
  65. return browsing_context.container_document()->origin();
  66. }
  67. // 5. Return url's origin.
  68. return URL::url_origin(*url);
  69. }
  70. // https://html.spec.whatwg.org/multipage/document-sequences.html#determining-the-origin
  71. HTML::Origin determine_the_origin(AK::URL const& url, SandboxingFlagSet sandbox_flags, Optional<HTML::Origin> source_origin, Optional<HTML::Origin> container_origin)
  72. {
  73. // 1. If sandboxFlags has its sandboxed origin browsing context flag set, then return a new opaque origin.
  74. if (sandbox_flags.flags & SandboxingFlagSet::SandboxedOrigin) {
  75. return HTML::Origin {};
  76. }
  77. // FIXME: 2. If url is null, then return a new opaque origin.
  78. // FIXME: There appears to be no way to get a null URL here, so it might be a spec bug.
  79. // 3. If url is about:srcdoc, then:
  80. if (url == "about:srcdoc"sv) {
  81. // 1. Assert: containerOrigin is non-null.
  82. VERIFY(container_origin.has_value());
  83. // 2. Return containerOrigin.
  84. return container_origin.release_value();
  85. }
  86. // 4. If url matches about:blank and sourceOrigin is non-null, then return sourceOrigin.
  87. if (url_matches_about_blank(url) && source_origin.has_value())
  88. return source_origin.release_value();
  89. // 5. Return url's origin.
  90. return URL::url_origin(url);
  91. }
  92. // https://html.spec.whatwg.org/multipage/browsers.html#creating-a-new-top-level-browsing-context
  93. JS::NonnullGCPtr<BrowsingContext> BrowsingContext::create_a_new_top_level_browsing_context(Web::Page& page)
  94. {
  95. // 1. Let group be the result of creating a new browsing context group.
  96. auto group = BrowsingContextGroup::create_a_new_browsing_context_group(page);
  97. // 2. Return group's browsing context set[0].
  98. return *group->browsing_context_set().begin();
  99. }
  100. // https://html.spec.whatwg.org/multipage/browsers.html#creating-a-new-browsing-context
  101. JS::NonnullGCPtr<BrowsingContext> BrowsingContext::create_a_new_browsing_context(Page& page, JS::GCPtr<DOM::Document> creator, JS::GCPtr<DOM::Element> embedder, BrowsingContextGroup&)
  102. {
  103. // 1. Let browsingContext be a new browsing context.
  104. NavigableContainer* container = (embedder && is<NavigableContainer>(*embedder)) ? static_cast<NavigableContainer*>(embedder.ptr()) : nullptr;
  105. auto browsing_context = Bindings::main_thread_vm().heap().allocate_without_realm<BrowsingContext>(page, container);
  106. // 2. Let unsafeContextCreationTime be the unsafe shared current time.
  107. [[maybe_unused]] auto unsafe_context_creation_time = HighResolutionTime::unsafe_shared_current_time();
  108. // 3. If creator is non-null, then set browsingContext's creator origin to return creator's origin,
  109. // browsingContext's creator URL to return creator's URL,
  110. // browsingContext's creator base URL to return creator's base URL,
  111. // FIXME: and browsingContext's virtual browsing context group ID to creator's top-level browsing context's virtual browsing context group ID.
  112. if (creator) {
  113. browsing_context->m_creator_origin = creator->origin();
  114. browsing_context->m_creator_url = creator->url();
  115. browsing_context->m_creator_base_url = creator->base_url();
  116. }
  117. // FIXME: 4. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and embedded.
  118. SandboxingFlagSet sandbox_flags;
  119. // 5. Let origin be the result of determining the origin given browsingContext, about:blank, sandboxFlags, and browsingContext's creator origin.
  120. auto origin = determine_the_origin(*browsing_context, AK::URL("about:blank"), sandbox_flags, browsing_context->m_creator_origin);
  121. // FIXME: 6. Let permissionsPolicy be the result of creating a permissions policy given browsingContext and origin. [PERMISSIONSPOLICY]
  122. // FIXME: 7. Let agent be the result of obtaining a similar-origin window agent given origin, group, and false.
  123. JS::GCPtr<Window> window;
  124. // 8. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
  125. auto realm_execution_context = Bindings::create_a_new_javascript_realm(
  126. Bindings::main_thread_vm(),
  127. [&](JS::Realm& realm) -> JS::Object* {
  128. browsing_context->m_window_proxy = realm.heap().allocate<WindowProxy>(realm, realm).release_allocated_value_but_fixme_should_propagate_errors();
  129. // - For the global object, create a new Window object.
  130. window = HTML::Window::create(realm).release_value_but_fixme_should_propagate_errors();
  131. return window.ptr();
  132. },
  133. [&](JS::Realm&) -> JS::Object* {
  134. // - For the global this binding, use browsingContext's WindowProxy object.
  135. return browsing_context->m_window_proxy;
  136. });
  137. // 9. Let topLevelCreationURL be about:blank if embedder is null; otherwise embedder's relevant settings object's top-level creation URL.
  138. auto top_level_creation_url = !embedder ? AK::URL("about:blank") : relevant_settings_object(*embedder).top_level_creation_url;
  139. // 10. Let topLevelOrigin be origin if embedder is null; otherwise embedder's relevant settings object's top-level origin.
  140. auto top_level_origin = !embedder ? origin : relevant_settings_object(*embedder).origin();
  141. // 11. Set up a window environment settings object with about:blank, realm execution context, null, topLevelCreationURL, and topLevelOrigin.
  142. HTML::WindowEnvironmentSettingsObject::setup(
  143. AK::URL("about:blank"),
  144. move(realm_execution_context),
  145. {},
  146. top_level_creation_url,
  147. top_level_origin)
  148. .release_value_but_fixme_should_propagate_errors();
  149. // 12. Let loadTimingInfo be a new document load timing info with its navigation start time set to the result of calling
  150. // coarsen time with unsafeContextCreationTime and the new environment settings object's cross-origin isolated capability.
  151. auto load_timing_info = DOM::DocumentLoadTimingInfo();
  152. load_timing_info.navigation_start_time = HighResolutionTime::coarsen_time(
  153. unsafe_context_creation_time,
  154. verify_cast<WindowEnvironmentSettingsObject>(Bindings::host_defined_environment_settings_object(window->realm())).cross_origin_isolated_capability() == CanUseCrossOriginIsolatedAPIs::Yes);
  155. // 13. Let coop be a new cross-origin opener policy.
  156. auto coop = CrossOriginOpenerPolicy {};
  157. // 14. If creator is non-null and creator's origin is same origin with creator's relevant settings object's top-level origin,
  158. // then set coop to creator's browsing context's top-level browsing context's active document's cross-origin opener policy.
  159. if (creator && creator->origin().is_same_origin(relevant_settings_object(*creator).top_level_origin)) {
  160. VERIFY(creator->browsing_context());
  161. auto* top_level_document = creator->browsing_context()->top_level_browsing_context().active_document();
  162. VERIFY(top_level_document);
  163. coop = top_level_document->cross_origin_opener_policy();
  164. }
  165. // 15. Let document be a new Document, marked as an HTML document in quirks mode,
  166. // whose content type is "text/html",
  167. // origin is origin,
  168. // FIXME: active sandboxing flag set is sandboxFlags,
  169. // FIXME: permissions policy is permissionsPolicy,
  170. // cross-origin opener policy is coop,
  171. // load timing info is loadTimingInfo,
  172. // FIXME: navigation id is null,
  173. // and which is ready for post-load tasks.
  174. auto document = HTML::HTMLDocument::create(window->realm()).release_value_but_fixme_should_propagate_errors();
  175. // Non-standard
  176. document->set_window(*window);
  177. window->set_associated_document(*document);
  178. document->set_quirks_mode(DOM::QuirksMode::Yes);
  179. document->set_content_type("text/html");
  180. document->set_origin(origin);
  181. document->set_url(AK::URL("about:blank"));
  182. document->set_cross_origin_opener_policy(coop);
  183. document->set_load_timing_info(load_timing_info);
  184. document->set_ready_for_post_load_tasks(true);
  185. // FIXME: 16. Assert: document's URL and document's relevant settings object's creation URL are about:blank.
  186. // 17. Set document's is initial about:blank to true.
  187. document->set_is_initial_about_blank(true);
  188. // 18. Ensure that document has a single child html node, which itself has two empty child nodes: a head element, and a body element.
  189. auto html_node = DOM::create_element(document, HTML::TagNames::html, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  190. MUST(html_node->append_child(DOM::create_element(document, HTML::TagNames::head, Namespace::HTML).release_value_but_fixme_should_propagate_errors()));
  191. MUST(html_node->append_child(DOM::create_element(document, HTML::TagNames::body, Namespace::HTML).release_value_but_fixme_should_propagate_errors()));
  192. MUST(document->append_child(html_node));
  193. // 19. Set the active document of browsingContext to document.
  194. browsing_context->set_active_document(*document);
  195. // 20. If browsingContext's creator URL is non-null, then set document's referrer to the serialization of it.
  196. if (browsing_context->m_creator_url.has_value()) {
  197. document->set_referrer(browsing_context->m_creator_url->serialize());
  198. }
  199. // FIXME: 21. If creator is non-null, then set document's policy container to a clone of creator's policy container.
  200. // 22. Append a new session history entry to browsingContext's session history whose URL is about:blank and document is document.
  201. auto new_entry = browsing_context->heap().allocate_without_realm<SessionHistoryEntry>();
  202. new_entry->url = AK::URL("about:blank");
  203. new_entry->document = document.ptr();
  204. new_entry->serialized_state = {};
  205. new_entry->policy_container = {};
  206. new_entry->scroll_restoration_mode = {};
  207. new_entry->browsing_context_name = {};
  208. new_entry->original_source_browsing_context = {};
  209. browsing_context->m_session_history.append(*new_entry);
  210. // 23. Completely finish loading document.
  211. document->completely_finish_loading();
  212. // 24. Return browsingContext.
  213. return *browsing_context;
  214. }
  215. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-auxiliary-browsing-context
  216. WebIDL::ExceptionOr<BrowsingContext::BrowsingContextAndDocument> BrowsingContext::create_a_new_auxiliary_browsing_context_and_document(Page& page, JS::NonnullGCPtr<HTML::BrowsingContext> opener)
  217. {
  218. // 1. Let openerTopLevelBrowsingContext be opener's top-level traversable's active browsing context.
  219. auto opener_top_level_browsing_context = opener->top_level_traversable()->active_browsing_context();
  220. // 2. Let group be openerTopLevelBrowsingContext's group.
  221. auto group = opener_top_level_browsing_context->group();
  222. // 3. Assert: group is non-null, as navigating invokes this directly.
  223. VERIFY(group);
  224. // 4. Set browsingContext and document be the result of creating a new browsing context and document with opener's active document, null, and group.
  225. auto [browsing_context, document] = TRY(create_a_new_browsing_context_and_document(page, opener->active_document(), nullptr, *group));
  226. // FIXME: 5. Set browsingContext's is auxiliary to true.
  227. // 6. Append browsingContext to group.
  228. group->append(browsing_context);
  229. // 7. Set browsingContext's opener browsing context to opener.
  230. browsing_context->set_opener_browsing_context(opener);
  231. // FIXME: 8. Set browsingContext's virtual browsing context group ID to openerTopLevelBrowsingContext's virtual browsing context group ID.
  232. // FIXME: 9. Set browsingContext's opener origin at creation to opener's active document's origin.
  233. // 10. Return browsingContext and document.
  234. return BrowsingContext::BrowsingContextAndDocument { browsing_context, document };
  235. }
  236. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-browsing-context
  237. WebIDL::ExceptionOr<BrowsingContext::BrowsingContextAndDocument> BrowsingContext::create_a_new_browsing_context_and_document(Page& page, JS::GCPtr<DOM::Document> creator, JS::GCPtr<DOM::Element> embedder, JS::NonnullGCPtr<BrowsingContextGroup> group)
  238. {
  239. auto& vm = group->vm();
  240. // 1. Let browsingContext be a new browsing context.
  241. JS::NonnullGCPtr<BrowsingContext> browsing_context = *vm.heap().allocate_without_realm<BrowsingContext>(page, nullptr);
  242. // 2. Let unsafeContextCreationTime be the unsafe shared current time.
  243. [[maybe_unused]] auto unsafe_context_creation_time = HighResolutionTime::unsafe_shared_current_time();
  244. // 3. Let creatorOrigin be null.
  245. Optional<Origin> creator_origin = {};
  246. // 4. If creator is non-null, then:
  247. if (creator) {
  248. // 1. Set creatorOrigin to creator's origin.
  249. creator_origin = creator->origin();
  250. // FIXME: 2. Set browsingContext's creator base URL to an algorithm which returns creator's base URL.
  251. // FIXME: 3. Set browsingContext's virtual browsing context group ID to creator's browsing context's top-level browsing context's virtual browsing context group ID.
  252. }
  253. // FIXME: 5. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and embedder.
  254. SandboxingFlagSet sandbox_flags;
  255. // 6. Let origin be the result of determining the origin given about:blank, sandboxFlags, creatorOrigin, and null.
  256. auto origin = determine_the_origin(AK::URL("about:blank"sv), sandbox_flags, creator_origin, {});
  257. // FIXME: 7. Let permissionsPolicy be the result of creating a permissions policy given browsingContext and origin. [PERMISSIONSPOLICY]
  258. // FIXME: 8. Let agent be the result of obtaining a similar-origin window agent given origin, group, and false.
  259. JS::GCPtr<Window> window;
  260. // 9. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
  261. auto realm_execution_context = Bindings::create_a_new_javascript_realm(
  262. Bindings::main_thread_vm(),
  263. [&](JS::Realm& realm) -> JS::Object* {
  264. auto window_proxy = realm.heap().allocate<WindowProxy>(realm, realm);
  265. browsing_context->set_window_proxy(window_proxy.release_allocated_value_but_fixme_should_propagate_errors());
  266. // - For the global object, create a new Window object.
  267. window = Window::create(realm).release_value_but_fixme_should_propagate_errors();
  268. return window.ptr();
  269. },
  270. [&](JS::Realm&) -> JS::Object* {
  271. // - For the global this binding, use browsingContext's WindowProxy object.
  272. return browsing_context->window_proxy();
  273. });
  274. // 10. Let topLevelCreationURL be about:blank if embedder is null; otherwise embedder's relevant settings object's top-level creation URL.
  275. auto top_level_creation_url = !embedder ? AK::URL("about:blank") : relevant_settings_object(*embedder).top_level_creation_url;
  276. // 11. Let topLevelOrigin be origin if embedder is null; otherwise embedder's relevant settings object's top-level origin.
  277. auto top_level_origin = !embedder ? origin : relevant_settings_object(*embedder).origin();
  278. // 12. Set up a window environment settings object with about:blank, realm execution context, null, topLevelCreationURL, and topLevelOrigin.
  279. TRY(WindowEnvironmentSettingsObject::setup(
  280. AK::URL("about:blank"),
  281. move(realm_execution_context),
  282. {},
  283. top_level_creation_url,
  284. top_level_origin));
  285. // 13. Let loadTimingInfo be a new document load timing info with its navigation start time set to the result of calling
  286. // coarsen time with unsafeContextCreationTime and the new environment settings object's cross-origin isolated capability.
  287. auto load_timing_info = DOM::DocumentLoadTimingInfo();
  288. load_timing_info.navigation_start_time = HighResolutionTime::coarsen_time(
  289. unsafe_context_creation_time,
  290. verify_cast<WindowEnvironmentSettingsObject>(Bindings::host_defined_environment_settings_object(window->realm())).cross_origin_isolated_capability() == CanUseCrossOriginIsolatedAPIs::Yes);
  291. // 14. Let document be a new Document, with:
  292. auto document = TRY(HTML::HTMLDocument::create(window->realm()));
  293. // Non-standard
  294. document->set_window(*window);
  295. window->set_associated_document(*document);
  296. // type: "html"
  297. document->set_document_type(DOM::Document::Type::HTML);
  298. // content type: "text/html"
  299. document->set_content_type("text/html");
  300. // mode: "quirks"
  301. document->set_quirks_mode(DOM::QuirksMode::Yes);
  302. // origin: origin
  303. document->set_origin(origin);
  304. // browsing context: browsingContext
  305. document->set_browsing_context(browsing_context);
  306. // FIXME: permissions policy: permissionsPolicy
  307. // FIXME: active sandboxing flag set: sandboxFlags
  308. // load timing info: loadTimingInfo
  309. document->set_load_timing_info(load_timing_info);
  310. // is initial about:blank: true
  311. document->set_is_initial_about_blank(true);
  312. // 15. If creator is non-null, then:
  313. if (creator) {
  314. // 1. Set document's referrer to the serialization of creator's URL.
  315. document->set_referrer(creator->url().serialize());
  316. // FIXME: 2. Set document's policy container to a clone of creator's policy container.
  317. // 3. If creator's origin is same origin with creator's relevant settings object's top-level origin,
  318. if (creator->origin().is_same_origin(creator->relevant_settings_object().top_level_origin)) {
  319. // then set document's cross-origin opener policy to creator's browsing context's top-level browsing context's active document's cross-origin opener policy.
  320. VERIFY(creator->browsing_context());
  321. VERIFY(creator->browsing_context()->top_level_browsing_context().active_document());
  322. document->set_cross_origin_opener_policy(creator->browsing_context()->top_level_browsing_context().active_document()->cross_origin_opener_policy());
  323. }
  324. }
  325. // 16. Assert: document's URL and document's relevant settings object's creation URL are about:blank.
  326. VERIFY(document->url() == "about:blank"sv);
  327. VERIFY(document->relevant_settings_object().creation_url == "about:blank"sv);
  328. // 17. Mark document as ready for post-load tasks.
  329. document->set_ready_for_post_load_tasks(true);
  330. // 18. Ensure that document has a single child html node, which itself has two empty child nodes: a head element, and a body element.
  331. auto html_node = TRY(DOM::create_element(document, HTML::TagNames::html, Namespace::HTML));
  332. auto head_element = TRY(DOM::create_element(document, HTML::TagNames::head, Namespace::HTML));
  333. TRY(html_node->append_child(head_element));
  334. auto body_element = TRY(DOM::create_element(document, HTML::TagNames::body, Namespace::HTML));
  335. TRY(html_node->append_child(body_element));
  336. TRY(document->append_child(html_node));
  337. // 19. Make active document.
  338. document->make_active();
  339. // 20. Completely finish loading document.
  340. document->completely_finish_loading();
  341. // 21. Return browsingContext and document.
  342. return BrowsingContext::BrowsingContextAndDocument { browsing_context, document };
  343. }
  344. BrowsingContext::BrowsingContext(Page& page, HTML::NavigableContainer* container)
  345. : m_page(page)
  346. , m_loader(*this)
  347. , m_event_handler({}, *this)
  348. , m_container(container)
  349. {
  350. m_cursor_blink_timer = Platform::Timer::create_repeating(500, [this] {
  351. if (!is_focused_context())
  352. return;
  353. if (m_cursor_position.node() && m_cursor_position.node()->layout_node()) {
  354. m_cursor_blink_state = !m_cursor_blink_state;
  355. m_cursor_position.node()->layout_node()->set_needs_display();
  356. }
  357. });
  358. }
  359. BrowsingContext::~BrowsingContext() = default;
  360. void BrowsingContext::visit_edges(Cell::Visitor& visitor)
  361. {
  362. Base::visit_edges(visitor);
  363. for (auto& entry : m_session_history)
  364. visitor.visit(entry);
  365. visitor.visit(m_container);
  366. visitor.visit(m_window_proxy);
  367. visitor.visit(m_opener_browsing_context);
  368. visitor.visit(m_group);
  369. visitor.visit(m_parent);
  370. visitor.visit(m_first_child);
  371. visitor.visit(m_last_child);
  372. visitor.visit(m_next_sibling);
  373. visitor.visit(m_previous_sibling);
  374. }
  375. // https://html.spec.whatwg.org/multipage/document-sequences.html#bc-traversable
  376. JS::NonnullGCPtr<HTML::TraversableNavigable> BrowsingContext::top_level_traversable() const
  377. {
  378. // A browsing context's top-level traversable is its active document's node navigable's top-level traversable.
  379. auto traversable = active_document()->navigable()->top_level_traversable();
  380. VERIFY(traversable);
  381. VERIFY(traversable->is_top_level_traversable());
  382. return *traversable;
  383. }
  384. void BrowsingContext::did_edit(Badge<EditEventHandler>)
  385. {
  386. reset_cursor_blink_cycle();
  387. if (m_cursor_position.node() && is<DOM::Text>(*m_cursor_position.node())) {
  388. auto& text_node = static_cast<DOM::Text&>(*m_cursor_position.node());
  389. if (auto* input_element = text_node.owner_input_element())
  390. input_element->did_edit_text_node({});
  391. }
  392. }
  393. void BrowsingContext::reset_cursor_blink_cycle()
  394. {
  395. m_cursor_blink_state = true;
  396. m_cursor_blink_timer->restart();
  397. if (m_cursor_position.is_valid() && m_cursor_position.node()->layout_node())
  398. m_cursor_position.node()->layout_node()->set_needs_display();
  399. }
  400. // https://html.spec.whatwg.org/multipage/browsers.html#top-level-browsing-context
  401. bool BrowsingContext::is_top_level() const
  402. {
  403. // A browsing context that has no parent browsing context is the top-level browsing context for itself and all of the browsing contexts for which it is an ancestor browsing context.
  404. return !parent();
  405. }
  406. bool BrowsingContext::is_focused_context() const
  407. {
  408. return m_page && &m_page->focused_context() == this;
  409. }
  410. // https://html.spec.whatwg.org/multipage/browsers.html#set-the-active-document
  411. void BrowsingContext::set_active_document(JS::NonnullGCPtr<DOM::Document> document)
  412. {
  413. auto previously_active_document = active_document();
  414. // 1. Let window be document's relevant global object.
  415. auto& window = verify_cast<HTML::Window>(relevant_global_object(document));
  416. // 2. Set document's visibility state to browsingContext's top-level browsing context's system visibility state.
  417. document->set_visibility_state({}, top_level_browsing_context().system_visibility_state());
  418. // 3. Set browsingContext's active window to window.
  419. m_window_proxy->set_window(window);
  420. // 4. Set window's associated Document to document.
  421. window.set_associated_document(document);
  422. // 5. Set window's relevant settings object's execution ready flag.
  423. relevant_settings_object(window).execution_ready = true;
  424. // AD-HOC:
  425. document->set_browsing_context(this);
  426. if (m_page && m_page->top_level_browsing_context_is_initialized() && this == &m_page->top_level_browsing_context())
  427. m_page->client().page_did_change_title(document->title());
  428. if (previously_active_document && previously_active_document != document.ptr())
  429. previously_active_document->did_stop_being_active_document_in_browsing_context({});
  430. }
  431. void BrowsingContext::inform_all_viewport_clients_about_the_current_viewport_rect()
  432. {
  433. for (auto* client : m_viewport_clients)
  434. client->browsing_context_did_set_viewport_rect(viewport_rect());
  435. }
  436. void BrowsingContext::set_viewport_rect(CSSPixelRect const& rect)
  437. {
  438. bool did_change = false;
  439. if (m_size != rect.size()) {
  440. m_size = rect.size();
  441. if (auto* document = active_document()) {
  442. // NOTE: Resizing the viewport changes the reference value for viewport-relative CSS lengths.
  443. document->invalidate_style();
  444. document->set_needs_layout();
  445. }
  446. did_change = true;
  447. }
  448. if (m_viewport_scroll_offset != rect.location()) {
  449. m_viewport_scroll_offset = rect.location();
  450. scroll_offset_did_change();
  451. did_change = true;
  452. }
  453. if (did_change) {
  454. for (auto* client : m_viewport_clients)
  455. client->browsing_context_did_set_viewport_rect(rect);
  456. }
  457. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  458. HTML::main_thread_event_loop().schedule();
  459. }
  460. void BrowsingContext::set_size(CSSPixelSize size)
  461. {
  462. if (m_size == size)
  463. return;
  464. m_size = size;
  465. if (auto* document = active_document()) {
  466. document->invalidate_style();
  467. document->set_needs_layout();
  468. }
  469. for (auto* client : m_viewport_clients)
  470. client->browsing_context_did_set_viewport_rect(viewport_rect());
  471. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  472. HTML::main_thread_event_loop().schedule();
  473. }
  474. void BrowsingContext::set_needs_display()
  475. {
  476. set_needs_display(viewport_rect());
  477. }
  478. void BrowsingContext::set_needs_display(CSSPixelRect const& rect)
  479. {
  480. if (!viewport_rect().intersects(rect))
  481. return;
  482. if (is_top_level()) {
  483. if (m_page)
  484. m_page->client().page_did_invalidate(to_top_level_rect(rect));
  485. return;
  486. }
  487. if (container() && container()->layout_node())
  488. container()->layout_node()->set_needs_display();
  489. }
  490. void BrowsingContext::scroll_to(CSSPixelPoint position)
  491. {
  492. // NOTE: Scrolling to a position requires up-to-date layout *unless* we're scrolling to (0, 0)
  493. // as (0, 0) is always guaranteed to be a valid scroll position.
  494. if (!position.is_zero()) {
  495. if (active_document())
  496. active_document()->update_layout();
  497. }
  498. if (m_page && this == &m_page->top_level_browsing_context())
  499. m_page->client().page_did_request_scroll_to(position);
  500. }
  501. void BrowsingContext::scroll_to_anchor(DeprecatedString const& fragment)
  502. {
  503. JS::GCPtr<DOM::Document> document = active_document();
  504. if (!document)
  505. return;
  506. auto element = document->get_element_by_id(fragment);
  507. if (!element) {
  508. auto candidates = document->get_elements_by_name(fragment);
  509. for (auto& candidate : candidates->collect_matching_elements()) {
  510. if (is<HTML::HTMLAnchorElement>(*candidate)) {
  511. element = &verify_cast<HTML::HTMLAnchorElement>(*candidate);
  512. break;
  513. }
  514. }
  515. }
  516. if (!element)
  517. return;
  518. document->update_layout();
  519. if (!element->layout_node())
  520. return;
  521. auto& layout_node = *element->layout_node();
  522. CSSPixelRect target_rect { layout_node.box_type_agnostic_position(), { viewport_rect().width(), viewport_rect().height() } };
  523. if (is<Layout::Box>(layout_node)) {
  524. auto& layout_box = verify_cast<Layout::Box>(layout_node);
  525. auto padding_box = layout_box.box_model().padding_box();
  526. target_rect.translate_by(-padding_box.left, -padding_box.top);
  527. }
  528. if (m_page && this == &m_page->top_level_browsing_context())
  529. m_page->client().page_did_request_scroll_into_view(target_rect);
  530. }
  531. CSSPixelRect BrowsingContext::to_top_level_rect(CSSPixelRect const& a_rect)
  532. {
  533. auto rect = a_rect;
  534. rect.set_location(to_top_level_position(a_rect.location()));
  535. return rect;
  536. }
  537. CSSPixelPoint BrowsingContext::to_top_level_position(CSSPixelPoint a_position)
  538. {
  539. auto position = a_position;
  540. for (auto ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  541. if (ancestor->is_top_level())
  542. break;
  543. if (!ancestor->container())
  544. return {};
  545. if (!ancestor->container()->layout_node())
  546. return {};
  547. position.translate_by(ancestor->container()->layout_node()->box_type_agnostic_position());
  548. }
  549. return position;
  550. }
  551. void BrowsingContext::set_cursor_position(DOM::Position position)
  552. {
  553. if (m_cursor_position == position)
  554. return;
  555. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  556. m_cursor_position.node()->layout_node()->set_needs_display();
  557. m_cursor_position = move(position);
  558. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  559. m_cursor_position.node()->layout_node()->set_needs_display();
  560. reset_cursor_blink_cycle();
  561. }
  562. static DeprecatedString visible_text_in_range(DOM::Range const& range)
  563. {
  564. // NOTE: This is an adaption of Range stringification, but we skip over DOM nodes that don't have a corresponding layout node.
  565. StringBuilder builder;
  566. if (range.start_container() == range.end_container() && is<DOM::Text>(*range.start_container())) {
  567. if (!range.start_container()->layout_node())
  568. return ""sv;
  569. return static_cast<DOM::Text const&>(*range.start_container()).data().substring(range.start_offset(), range.end_offset() - range.start_offset());
  570. }
  571. if (is<DOM::Text>(*range.start_container()) && range.start_container()->layout_node())
  572. builder.append(static_cast<DOM::Text const&>(*range.start_container()).data().substring_view(range.start_offset()));
  573. for (DOM::Node const* node = range.start_container(); node != range.end_container()->next_sibling(); node = node->next_in_pre_order()) {
  574. if (is<DOM::Text>(*node) && range.contains_node(*node) && node->layout_node())
  575. builder.append(static_cast<DOM::Text const&>(*node).data());
  576. }
  577. if (is<DOM::Text>(*range.end_container()) && range.end_container()->layout_node())
  578. builder.append(static_cast<DOM::Text const&>(*range.end_container()).data().substring_view(0, range.end_offset()));
  579. return builder.to_deprecated_string();
  580. }
  581. DeprecatedString BrowsingContext::selected_text() const
  582. {
  583. auto* document = active_document();
  584. if (!document)
  585. return ""sv;
  586. auto selection = const_cast<DOM::Document&>(*document).get_selection();
  587. auto range = selection->range();
  588. if (!range)
  589. return ""sv;
  590. return visible_text_in_range(*range);
  591. }
  592. void BrowsingContext::select_all()
  593. {
  594. auto* document = active_document();
  595. if (!document)
  596. return;
  597. auto* body = document->body();
  598. if (!body)
  599. return;
  600. auto selection = document->get_selection();
  601. if (!selection)
  602. return;
  603. (void)selection->select_all_children(*document->body());
  604. }
  605. void BrowsingContext::register_viewport_client(ViewportClient& client)
  606. {
  607. auto result = m_viewport_clients.set(&client);
  608. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  609. }
  610. void BrowsingContext::unregister_viewport_client(ViewportClient& client)
  611. {
  612. bool was_removed = m_viewport_clients.remove(&client);
  613. VERIFY(was_removed);
  614. }
  615. void BrowsingContext::register_frame_nesting(AK::URL const& url)
  616. {
  617. m_frame_nesting_levels.ensure(url)++;
  618. }
  619. bool BrowsingContext::is_frame_nesting_allowed(AK::URL const& url) const
  620. {
  621. return m_frame_nesting_levels.get(url).value_or(0) < 3;
  622. }
  623. bool BrowsingContext::increment_cursor_position_offset()
  624. {
  625. if (!m_cursor_position.increment_offset())
  626. return false;
  627. reset_cursor_blink_cycle();
  628. return true;
  629. }
  630. bool BrowsingContext::decrement_cursor_position_offset()
  631. {
  632. if (!m_cursor_position.decrement_offset())
  633. return false;
  634. reset_cursor_blink_cycle();
  635. return true;
  636. }
  637. DOM::Document* BrowsingContext::container_document()
  638. {
  639. if (auto* container = this->container())
  640. return &container->document();
  641. return nullptr;
  642. }
  643. DOM::Document const* BrowsingContext::container_document() const
  644. {
  645. if (auto* container = this->container())
  646. return &container->document();
  647. return nullptr;
  648. }
  649. // https://html.spec.whatwg.org/#rendering-opportunity
  650. bool BrowsingContext::has_a_rendering_opportunity() const
  651. {
  652. // A browsing context has a rendering opportunity if the user agent is currently able to present the contents of the browsing context to the user,
  653. // accounting for hardware refresh rate constraints and user agent throttling for performance reasons, but considering content presentable even if it's outside the viewport.
  654. // FIXME: We should at the very least say `false` here if we're an inactive browser tab.
  655. return true;
  656. }
  657. // https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-browsing-context
  658. JS::GCPtr<DOM::Node> BrowsingContext::currently_focused_area()
  659. {
  660. // 1. If topLevelBC does not have system focus, then return null.
  661. if (!is_focused_context())
  662. return nullptr;
  663. // 2. Let candidate be topLevelBC's active document.
  664. auto* candidate = active_document();
  665. // 3. While candidate's focused area is a browsing context container with a non-null nested browsing context:
  666. // set candidate to the active document of that browsing context container's nested browsing context.
  667. while (candidate->focused_element()
  668. && is<HTML::NavigableContainer>(candidate->focused_element())
  669. && static_cast<HTML::NavigableContainer&>(*candidate->focused_element()).nested_browsing_context()) {
  670. candidate = static_cast<HTML::NavigableContainer&>(*candidate->focused_element()).nested_browsing_context()->active_document();
  671. }
  672. // 4. If candidate's focused area is non-null, set candidate to candidate's focused area.
  673. if (candidate->focused_element()) {
  674. // NOTE: We return right away here instead of assigning to candidate,
  675. // since that would require compromising type safety.
  676. return candidate->focused_element();
  677. }
  678. // 5. Return candidate.
  679. return candidate;
  680. }
  681. // https://html.spec.whatwg.org/#the-rules-for-choosing-a-browsing-context-given-a-browsing-context-name
  682. BrowsingContext::ChosenBrowsingContext BrowsingContext::choose_a_browsing_context(StringView name, TokenizedFeature::NoOpener no_opener, ActivateTab activate_tab)
  683. {
  684. // The rules for choosing a browsing context, given a browsing context name name, a browsing context current, and
  685. // a boolean noopener are as follows:
  686. JS::GCPtr<AbstractBrowsingContext> matching_name_in_tree = nullptr;
  687. top_level_browsing_context().for_each_in_subtree([&](auto& context) {
  688. if (context.name() == name) {
  689. matching_name_in_tree = &context;
  690. return IterationDecision::Break;
  691. }
  692. return IterationDecision::Continue;
  693. });
  694. // 1. Let chosen be null.
  695. JS::GCPtr<AbstractBrowsingContext> chosen = nullptr;
  696. // 2. Let windowType be "existing or none".
  697. auto window_type = WindowType::ExistingOrNone;
  698. // 3. Let sandboxingFlagSet be current's active document's active sandboxing flag set.
  699. auto sandboxing_flag_set = active_document()->active_sandboxing_flag_set();
  700. // 4. If name is the empty string or an ASCII case-insensitive match for "_self", then set chosen to current.
  701. if (name.is_empty() || Infra::is_ascii_case_insensitive_match(name, "_self"sv)) {
  702. chosen = this;
  703. }
  704. // 5. Otherwise, if name is an ASCII case-insensitive match for "_parent", set chosen to current's parent browsing
  705. // context, if any, and current otherwise.
  706. else if (Infra::is_ascii_case_insensitive_match(name, "_parent"sv)) {
  707. if (auto parent = this->parent())
  708. chosen = parent;
  709. else
  710. chosen = this;
  711. }
  712. // 6. Otherwise, if name is an ASCII case-insensitive match for "_top", set chosen to current's top-level browsing
  713. // context, if any, and current otherwise.
  714. else if (Infra::is_ascii_case_insensitive_match(name, "_top"sv)) {
  715. chosen = &top_level_browsing_context();
  716. }
  717. // 7. Otherwise, if name is not an ASCII case-insensitive match for "_blank", there exists a browsing context
  718. // whose name is the same as name, current is familiar with that browsing context, and the user agent
  719. // determines that the two browsing contexts are related enough that it is ok if they reach each other,
  720. // set chosen to that browsing context. If there are multiple matching browsing contexts, the user agent
  721. // should set chosen to one in some arbitrary consistent manner, such as the most recently opened, most
  722. // recently focused, or more closely related.
  723. else if (!Infra::is_ascii_case_insensitive_match(name, "_blank"sv) && matching_name_in_tree) {
  724. chosen = matching_name_in_tree;
  725. } else {
  726. // 8. Otherwise, a new browsing context is being requested, and what happens depends on the user agent's
  727. // configuration and abilities — it is determined by the rules given for the first applicable option from
  728. // the following list:
  729. // --> If current's active window does not have transient activation and the user agent has been configured to
  730. // not show popups (i.e., the user agent has a "popup blocker" enabled)
  731. VERIFY(m_page);
  732. if (!active_window()->has_transient_activation() && m_page->should_block_pop_ups()) {
  733. // FIXME: The user agent may inform the user that a popup has been blocked.
  734. dbgln("Pop-up blocked!");
  735. }
  736. // --> If sandboxingFlagSet has the sandboxed auxiliary navigation browsing context flag set
  737. else if (sandboxing_flag_set.flags & SandboxingFlagSet::SandboxedAuxiliaryNavigation) {
  738. // FIXME: The user agent may report to a developer console that a popup has been blocked.
  739. dbgln("Pop-up blocked!");
  740. }
  741. // --> If the user agent has been configured such that in this instance it will create a new browsing context
  742. else if (true) { // FIXME: When is this the case?
  743. // 1. Set windowType to "new and unrestricted".
  744. window_type = WindowType::NewAndUnrestricted;
  745. // 2. If current's top-level browsing context's active document's cross-origin opener policy's value is
  746. // "same-origin" or "same-origin-plus-COEP", then:
  747. if (top_level_browsing_context().active_document()->cross_origin_opener_policy().value == CrossOriginOpenerPolicyValue::SameOrigin || top_level_browsing_context().active_document()->cross_origin_opener_policy().value == CrossOriginOpenerPolicyValue::SameOriginPlusCOEP) {
  748. // 1. Let currentDocument be current's active document.
  749. auto* current_document = top_level_browsing_context().active_document();
  750. // 2. If currentDocument's origin is not same origin with currentDocument's relevant settings object's
  751. // top-level origin, then set noopener to true, name to "_blank", and windowType to "new with no opener".
  752. if (!current_document->origin().is_same_origin(current_document->relevant_settings_object().top_level_origin)) {
  753. no_opener = TokenizedFeature::NoOpener::Yes;
  754. name = "_blank"sv;
  755. window_type = WindowType::NewWithNoOpener;
  756. }
  757. }
  758. // 3. If noopener is true, then set chosen to the result of creating a new top-level browsing context.
  759. if (no_opener == TokenizedFeature::NoOpener::Yes) {
  760. auto handle = m_page->client().page_did_request_new_tab(activate_tab);
  761. chosen = RemoteBrowsingContext::create_a_new_remote_browsing_context(handle);
  762. }
  763. // 4. Otherwise:
  764. else {
  765. // 1. Set chosen to the result of creating a new auxiliary browsing context with current.
  766. // FIXME: We have no concept of auxiliary browsing context
  767. chosen = HTML::BrowsingContext::create_a_new_top_level_browsing_context(*m_page);
  768. // 2. If sandboxingFlagSet's sandboxed navigation browsing context flag is set, then current must be
  769. // set as chosen's one permitted sandboxed navigator.
  770. // FIXME: We have no concept of one permitted sandboxed navigator
  771. }
  772. // 5. If sandboxingFlagSet's sandbox propagates to auxiliary browsing contexts flag is set, then all the
  773. // flags that are set in sandboxingFlagSet must be set in chosen's popup sandboxing flag set.
  774. // FIXME: Our BrowsingContexts do not have SandboxingFlagSets yet, only documents do
  775. // 6. If name is not an ASCII case-insensitive match for "_blank", then set chosen's name to name.
  776. if (!Infra::is_ascii_case_insensitive_match(name, "_blank"sv))
  777. chosen->set_name(String::from_utf8(name).release_value_but_fixme_should_propagate_errors());
  778. }
  779. // --> If the user agent has been configured such that in this instance t will reuse current
  780. else if (false) { // FIXME: When is this the case?
  781. // Set chosen to current.
  782. chosen = *this;
  783. }
  784. // --> If the user agent has been configured such that in this instance it will not find a browsing context
  785. else if (false) { // FIXME: When is this the case?
  786. // Do nothing.
  787. }
  788. }
  789. // 9. Return chosen and windowType.
  790. return { chosen.ptr(), window_type };
  791. }
  792. // https://html.spec.whatwg.org/multipage/browsers.html#document-tree-child-browsing-context
  793. size_t BrowsingContext::document_tree_child_browsing_context_count() const
  794. {
  795. size_t count = 0;
  796. // A browsing context child is a document-tree child browsing context of parent if child is a child browsing context and child's container is in a document tree.
  797. for_each_child([this, &count](BrowsingContext const& child) {
  798. if (child.is_child_of(*this) && child.container()->in_a_document_tree())
  799. ++count;
  800. });
  801. return count;
  802. }
  803. // https://html.spec.whatwg.org/multipage/browsers.html#child-browsing-context
  804. bool BrowsingContext::is_child_of(BrowsingContext const& parent) const
  805. {
  806. // A browsing context child is said to be a child browsing context of another browsing context parent,
  807. // if child's container document is non-null and child's container document's browsing context is parent.
  808. return container_document() && container_document()->browsing_context() == &parent;
  809. }
  810. // https://html.spec.whatwg.org/multipage/dom.html#still-on-its-initial-about:blank-document
  811. bool BrowsingContext::still_on_its_initial_about_blank_document() const
  812. {
  813. // A browsing context browsingContext is still on its initial about:blank Document
  814. // if browsingContext's session history's size is 1
  815. // and browsingContext's session history[0]'s document's is initial about:blank is true.
  816. return m_session_history.size() == 1
  817. && m_session_history[0]->document
  818. && m_session_history[0]->document->is_initial_about_blank();
  819. }
  820. DOM::Document const* BrowsingContext::active_document() const
  821. {
  822. auto* window = active_window();
  823. if (!window)
  824. return nullptr;
  825. return &window->associated_document();
  826. }
  827. DOM::Document* BrowsingContext::active_document()
  828. {
  829. auto* window = active_window();
  830. if (!window)
  831. return nullptr;
  832. return &window->associated_document();
  833. }
  834. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  835. HTML::Window* BrowsingContext::active_window()
  836. {
  837. return m_window_proxy->window();
  838. }
  839. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  840. HTML::Window const* BrowsingContext::active_window() const
  841. {
  842. return m_window_proxy->window();
  843. }
  844. HTML::WindowProxy* BrowsingContext::window_proxy()
  845. {
  846. return m_window_proxy.ptr();
  847. }
  848. HTML::WindowProxy const* BrowsingContext::window_proxy() const
  849. {
  850. return m_window_proxy.ptr();
  851. }
  852. void BrowsingContext::set_window_proxy(JS::GCPtr<WindowProxy> window_proxy)
  853. {
  854. m_window_proxy = move(window_proxy);
  855. }
  856. void BrowsingContext::scroll_offset_did_change()
  857. {
  858. // https://w3c.github.io/csswg-drafts/cssom-view-1/#scrolling-events
  859. // Whenever a viewport gets scrolled (whether in response to user interaction or by an API), the user agent must run these steps:
  860. // 1. Let doc be the viewport’s associated Document.
  861. auto* doc = active_document();
  862. VERIFY(doc);
  863. // 2. If doc is already in doc’s pending scroll event targets, abort these steps.
  864. for (auto& target : doc->pending_scroll_event_targets()) {
  865. if (target.ptr() == doc)
  866. return;
  867. }
  868. // 3. Append doc to doc’s pending scroll event targets.
  869. doc->pending_scroll_event_targets().append(*doc);
  870. }
  871. BrowsingContextGroup* BrowsingContext::group()
  872. {
  873. return m_group;
  874. }
  875. void BrowsingContext::set_group(BrowsingContextGroup* group)
  876. {
  877. m_group = group;
  878. }
  879. // https://html.spec.whatwg.org/multipage/browsers.html#bcg-remove
  880. void BrowsingContext::remove()
  881. {
  882. // 1. Assert: browsingContext's group is non-null, because a browsing context only gets discarded once.
  883. VERIFY(group());
  884. // 2. Let group be browsingContext's group.
  885. JS::NonnullGCPtr<BrowsingContextGroup> group = *this->group();
  886. // 3. Set browsingContext's group to null.
  887. set_group(nullptr);
  888. // 4. Remove browsingContext from group's browsing context set.
  889. group->browsing_context_set().remove(*this);
  890. // 5. If group's browsing context set is empty, then remove group from the user agent's browsing context group set.
  891. // NOTE: This is done by ~BrowsingContextGroup() when the refcount reaches 0.
  892. }
  893. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
  894. WebIDL::ExceptionOr<void> BrowsingContext::navigate(
  895. JS::NonnullGCPtr<Fetch::Infrastructure::Request> resource,
  896. BrowsingContext& source_browsing_context,
  897. bool exceptions_enabled,
  898. HistoryHandlingBehavior history_handling,
  899. Optional<PolicyContainer> history_policy_container,
  900. DeprecatedString navigation_type,
  901. Optional<String> navigation_id,
  902. Function<void(JS::NonnullGCPtr<Fetch::Infrastructure::Response>)> process_response_end_of_body)
  903. {
  904. // 1. If resource is a URL, then set resource to a new request whose URL is resource.
  905. // NOTE: This function only accepts resources that are already a request, so this is irrelevant.
  906. // 2. If resource is a request and historyHandling is "reload", then set resource's reload-navigation flag.
  907. if (history_handling == HistoryHandlingBehavior::Reload)
  908. resource->set_reload_navigation(true);
  909. // 3. If the source browsing context is not allowed to navigate browsingContext, then:
  910. if (!source_browsing_context.is_allowed_to_navigate(*this)) {
  911. // 1. If exceptionsEnabled is given and is true, then throw a "SecurityError" DOMException.
  912. if (exceptions_enabled) {
  913. VERIFY(source_browsing_context.active_document());
  914. return WebIDL::SecurityError::create(source_browsing_context.active_document()->realm(), "Source browsing context not allowed to navigate"sv);
  915. }
  916. // FIXME: 2. Otherwise, the user agent may instead offer to open resource in a new top-level browsing context
  917. // or in the top-level browsing context of the source browsing context, at the user's option,
  918. // in which case the user agent must navigate that designated top-level browsing context
  919. // to resource as if the user had requested it independently.
  920. }
  921. // 4. If navigationId is null:
  922. if (!navigation_id.has_value()) {
  923. // 1. If historyHandling is "reload", and browsingContext's active document's navigation id is not null,
  924. if (history_handling == HistoryHandlingBehavior::Reload && active_document()->navigation_id().has_value()) {
  925. // let navigationId be browsingContext's active document's navigation id.
  926. navigation_id = active_document()->navigation_id();
  927. } else {
  928. // Otherwise let navigation id be the result of generating a random UUID. [UUID]
  929. // FIXME: Generate a UUID.
  930. navigation_id = "FIXME"_short_string;
  931. }
  932. }
  933. // FIXME: 5. If browsingContext's active document's unload counter is greater than 0,
  934. // then invoke WebDriver BiDi navigation failed
  935. // with a WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is resource's url
  936. // and return.
  937. // 6. If historyHandling is "default", and any of the following are true:
  938. // - browsingContext is still on its initial about:blank Document
  939. // - resource is a request whose URL equals browsingContext's active document's URL
  940. // - resource is a request whose URL's scheme is "javascript"
  941. if (history_handling == HistoryHandlingBehavior::Default
  942. && (still_on_its_initial_about_blank_document()
  943. || resource->url().equals(active_document()->url())
  944. || resource->url().scheme() == "javascript"sv)) {
  945. // then set historyHandling to "replace".
  946. history_handling = HistoryHandlingBehavior::Replace;
  947. }
  948. // 7. If historyHandling is not "reload", resource is a request,
  949. // resource's URL equals browsingContext's active document's URL with exclude fragments set to true,
  950. // and resource's URL's fragment is non-null, then:
  951. if (history_handling != HistoryHandlingBehavior::Reload
  952. && resource->url().equals(active_document()->url(), AK::URL::ExcludeFragment::Yes)
  953. && !resource->url().fragment().is_null()) {
  954. // 1. Navigate to a fragment given browsingContext, resource's URL, historyHandling, and navigationId.
  955. TRY(navigate_to_a_fragment(resource->url(), history_handling, *navigation_id));
  956. // 2. Return.
  957. return {};
  958. }
  959. // FIXME: 8. Let incumbentNavigationOrigin be the origin of the incumbent settings object,
  960. // or if no script was involved, the origin of the node document of the element that initiated the navigation.
  961. // FIXME: 9. Let initiatorPolicyContainer be a clone of the source browsing context's active document's policy container.
  962. // FIXME: 10. If resource is a request, then set resource's policy container to initiatorPolicyContainer.
  963. // FIXME: 11. Cancel any preexisting but not yet mature attempt to navigate browsingContext,
  964. // including canceling any instances of the fetch algorithm started by those attempts.
  965. // If one of those attempts has already created and initialized a new Document object,
  966. // abort that Document also.
  967. // (Navigation attempts that have matured already have session history entries,
  968. // and are therefore handled during the update the session history with the new page algorithm, later.)
  969. // FIXME: 12. Let unloadPromptResult be the result of calling prompt to unload with the active document of browsingContext.
  970. // If this instance of the navigation algorithm gets canceled while this step is running,
  971. // the prompt to unload algorithm must nonetheless be run to completion.
  972. // FIXME: 13. If unloadPromptResult is "refuse", then return a new WebDriver BiDi navigation status whose id is navigationId and status is "canceled".
  973. // 14. Abort the active document of browsingContext.
  974. active_document()->abort();
  975. // FIXME: 15. If browsingContext is a child browsing context, then put it in the delaying load events mode.
  976. // The user agent must take this child browsing context out of the delaying load events mode when this navigation algorithm later matures,
  977. // or when it terminates (whether due to having run all the steps, or being canceled, or being aborted),
  978. // whichever happens first.
  979. // FIXME: 16. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and browsingContext's container.
  980. // FIXME: 17. Let allowedToDownload be the result of running the allowed to download algorithm given the source browsing context and browsingContext.
  981. // 18. Let hasTransientActivation be true if the source browsing context's active window has transient activation; otherwise false.
  982. [[maybe_unused]] bool has_transient_activation = source_browsing_context.active_window()->has_transient_activation();
  983. // FIXME: 19. Invoke WebDriver BiDi navigation started with browsingContext, and a new WebDriver BiDi navigation status whose id is navigationId, url is resource's url, and status is "pending".
  984. // 20. Return, and continue running these steps in parallel.
  985. // FIXME: Implement the rest of this algorithm
  986. (void)history_policy_container;
  987. (void)navigation_type;
  988. (void)process_response_end_of_body;
  989. // AD-HOC:
  990. auto request = LoadRequest::create_for_url_on_page(resource->url(), page());
  991. request.set_method(DeprecatedString { resource->method() });
  992. for (auto& header : *resource->header_list()) {
  993. request.set_header(DeprecatedString { header.name.bytes() }, DeprecatedString { header.value.bytes() });
  994. }
  995. if (request.method() == "POST"sv) {
  996. if (resource->body().has<ByteBuffer>()) {
  997. auto const& byte_buffer = resource->body().get<ByteBuffer>();
  998. request.set_body(byte_buffer);
  999. request.set_header("Content-Length", DeprecatedString::number(byte_buffer.size()));
  1000. } else {
  1001. request.set_header("Content-Length", DeprecatedString::number(0));
  1002. }
  1003. }
  1004. loader().load(request, FrameLoader::Type::Navigation);
  1005. return {};
  1006. }
  1007. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate-fragid
  1008. WebIDL::ExceptionOr<void> BrowsingContext::navigate_to_a_fragment(AK::URL const& url, HistoryHandlingBehavior history_handling, String navigation_id)
  1009. {
  1010. // 1. If historyHandling is not "replace",
  1011. if (history_handling != HistoryHandlingBehavior::Replace) {
  1012. // FIXME: then remove all the entries in browsingContext's session history after the current entry.
  1013. // (If the current entry is the last entry in the session history, then no entries are removed.)
  1014. }
  1015. // 2. Remove any tasks queued by the history traversal task source that are associated with any Document objects
  1016. // in browsingContext's top-level browsing context's document family.
  1017. HTML::main_thread_event_loop().task_queue().remove_tasks_matching([&](HTML::Task const& task) {
  1018. return task.source() == Task::Source::HistoryTraversal
  1019. && task.document()
  1020. && top_level_browsing_context().document_family_contains(*task.document());
  1021. });
  1022. // 3. Append a new session history entry to the session history whose URL is url,
  1023. // document is the current entry's document,
  1024. // policy container is the current entry's policy-container
  1025. // and scroll restoration mode is the current entry's scroll restoration mode.
  1026. auto new_entry = heap().allocate_without_realm<SessionHistoryEntry>();
  1027. new_entry->url = url;
  1028. new_entry->document = current_entry().document;
  1029. new_entry->serialized_state = {};
  1030. new_entry->policy_container = current_entry().policy_container;
  1031. new_entry->scroll_restoration_mode = current_entry().scroll_restoration_mode;
  1032. new_entry->browsing_context_name = {};
  1033. new_entry->original_source_browsing_context = {};
  1034. m_session_history.append(*new_entry);
  1035. // 4. Traverse the history to the new entry, with historyHandling set to historyHandling.
  1036. // This will scroll to the fragment given in what is now the document's URL.
  1037. TRY(traverse_the_history(m_session_history.size() - 1, history_handling));
  1038. // FIXME: 5. Invoke WebDriver BiDi fragment navigated with browsingContext,
  1039. // and a new WebDriver BiDi navigation status whose id is navigationId, url is resource's url, and status is "complete".
  1040. (void)navigation_id;
  1041. return {};
  1042. }
  1043. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#traverse-the-history
  1044. WebIDL::ExceptionOr<void> BrowsingContext::traverse_the_history(size_t entry_index, HistoryHandlingBehavior history_handling, bool explicit_history_navigation)
  1045. {
  1046. auto entry = m_session_history[entry_index];
  1047. // 1. If entry's document is null, then:
  1048. if (!entry->document) {
  1049. // 1. Assert: historyHandling is "default".
  1050. VERIFY(history_handling == HistoryHandlingBehavior::Default);
  1051. // 2. Let request be a new request whose URL is entry's URL.
  1052. auto& vm = Bindings::main_thread_vm();
  1053. auto request = Fetch::Infrastructure::Request::create(vm);
  1054. request->set_url(entry->url);
  1055. // 3. If explicitHistoryNavigation is true, then set request's history-navigation flag.
  1056. if (explicit_history_navigation)
  1057. request->set_history_navigation(true);
  1058. // 4. Navigate the browsing context to request with historyHandling set to "entry update"
  1059. // and with historyPolicyContainer set to entry's policy container.
  1060. // The navigation must be done using the same source browsing context as was used the first time entry was created.
  1061. VERIFY(entry->original_source_browsing_context);
  1062. TRY(navigate(request, *entry->original_source_browsing_context, false, HistoryHandlingBehavior::EntryUpdate, entry->policy_container));
  1063. // 5. Return.
  1064. return {};
  1065. }
  1066. // FIXME: 2. Save persisted state to the current entry.
  1067. // 3. Let newDocument be entry's document.
  1068. JS::GCPtr<DOM::Document> new_document = entry->document.ptr();
  1069. // 4. Assert: newDocument's is initial about:blank is false,
  1070. // i.e., we never traverse back to the initial about:blank Document because it always gets replaced when we navigate away from it.
  1071. VERIFY(!new_document->is_initial_about_blank());
  1072. // 5. If newDocument is different than the current entry's document, or historyHandling is "entry update" or "reload", then:
  1073. if (new_document.ptr() != current_entry().document.ptr()
  1074. || history_handling == HistoryHandlingBehavior::EntryUpdate) {
  1075. // FIXME: 1. If newDocument's suspended timer handles is not empty:
  1076. // FIXME: 1. Assert: newDocument's suspension time is not zero.
  1077. // FIXME: 2. Let suspendDuration be the current high resolution time minus newDocument's suspension time.
  1078. // FIXME: 3. Let activeTimers be newDocument's relevant global object's map of active timers.
  1079. // FIXME: 4. For each handle in newDocument's suspended timer handles, if activeTimers[handle] exists, then increase activeTimers[handle] by suspendDuration.
  1080. }
  1081. // 2. Remove any tasks queued by the history traversal task source
  1082. // that are associated with any Document objects in the top-level browsing context's document family.
  1083. HTML::main_thread_event_loop().task_queue().remove_tasks_matching([&](HTML::Task const& task) {
  1084. return task.source() == Task::Source::HistoryTraversal
  1085. && task.document()
  1086. && top_level_browsing_context().document_family_contains(*task.document());
  1087. });
  1088. // 3. If newDocument's origin is not same origin with the current entry's document's origin, then:
  1089. if (!new_document->origin().is_same_origin(current_entry().document->origin())) {
  1090. // FIXME: 1. Let entriesToUpdate be all entries in the session history whose document's origin is same origin as the active document
  1091. // and that are contiguous with the current entry.
  1092. // FIXME: 2. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to the current browsing context name.
  1093. // FIXME: 3. If the browsing context is a top-level browsing context, but not an auxiliary browsing context whose disowned is false, then set the browsing context's name to the empty string.
  1094. }
  1095. // 4. Set the active document of the browsing context to newDocument.
  1096. set_active_document(*new_document);
  1097. // 5. If entry's browsing context name is not null, then:
  1098. if (entry->browsing_context_name.has_value()) {
  1099. // 1. Set the browsing context's name to entry's browsing context name.
  1100. m_name = *entry->browsing_context_name;
  1101. // FIXME: 2. Let entriesToUpdate be all entries in the session history whose document's origin is same origin as the new active document's origin and that are contiguous with entry.
  1102. // FIXME: 3. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to null.
  1103. }
  1104. // FIXME: 6. If newDocument has any form controls whose autofill field name is "off", invoke the reset algorithm of each of those elements.
  1105. // 7. If newDocument's current document readiness "complete",
  1106. if (new_document->ready_state() == "complete"sv) {
  1107. // then queue a global task on the DOM manipulation task source given newDocument's relevant global object to run the following steps:
  1108. queue_global_task(Task::Source::DOMManipulation, relevant_global_object(*new_document), [new_document] {
  1109. // 1. If newDocument's page showing flag is true, then abort these steps.
  1110. if (new_document->page_showing())
  1111. return;
  1112. // 2. Set newDocument's page showing flag to true.
  1113. new_document->set_page_showing(true);
  1114. // 3. Update the visibility state of newDocument to "hidden".
  1115. new_document->update_the_visibility_state(VisibilityState::Hidden);
  1116. // 4. Fire a page transition event named pageshow at newDocument's relevant global object with true.
  1117. auto& window = verify_cast<HTML::Window>(relevant_global_object(*new_document));
  1118. window.fire_a_page_transition_event(HTML::EventNames::pageshow, true);
  1119. });
  1120. }
  1121. // 6. Set newDocument's URL to entry's URL.
  1122. new_document->set_url(entry->url);
  1123. // 7. Let hashChanged be false, and let oldURL and newURL be null.
  1124. bool hash_changed = false;
  1125. Optional<AK::URL> old_url;
  1126. Optional<AK::URL> new_url;
  1127. // 8. If entry's URL's fragment is not identical to the current entry's URL's fragment,
  1128. // and entry's document equals the current entry's document,
  1129. if (entry->url.fragment() != current_entry().url.fragment()
  1130. && entry->document.ptr() == current_entry().document.ptr()) {
  1131. // then set hashChanged to true, set oldURL to the current entry's URL, and set newURL to entry's URL.
  1132. hash_changed = true;
  1133. old_url = current_entry().url;
  1134. new_url = entry->url;
  1135. }
  1136. // 9. If historyHandling is "replace", then remove the entry immediately before entry in the session history.
  1137. if (history_handling == HistoryHandlingBehavior::Replace) {
  1138. // FIXME: This is gnarly.
  1139. m_session_history.remove(entry_index - 1);
  1140. entry_index--;
  1141. entry = m_session_history[entry_index];
  1142. }
  1143. // 10. If entry's persisted user state is null, and its URL's fragment is non-null, then scroll to the fragment.
  1144. if (!entry->url.fragment().is_null()) {
  1145. // FIXME: Implement the full "scroll to the fragment" algorithm:
  1146. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#scroll-to-the-fragment-identifier
  1147. scroll_to_anchor(entry->url.fragment());
  1148. }
  1149. // 11. Set the current entry to entry.
  1150. m_session_history_index = entry_index;
  1151. // 12. Let targetRealm be the current Realm Record.
  1152. auto* target_realm = Bindings::main_thread_vm().current_realm();
  1153. VERIFY(target_realm);
  1154. // FIXME: 13. Let state be null.
  1155. // FIXME: 14. If entry's serialized state is not null, then set state to StructuredDeserialize(entry's serialized state, targetRealm).
  1156. // If this throws an exception, catch it and ignore the exception.
  1157. // FIXME: 15. Set newDocument's History object's state to state.
  1158. // FIXME: 16. Let stateChanged be true if newDocument has a latest entry, and that entry is not entry; otherwise let it be false.
  1159. // FIXME: 17. Set newDocument's latest entry to entry.
  1160. // FIXME: 18. If stateChanged is true, then fire an event named popstate at newDocument's relevant global object, using PopStateEvent, with the state attribute initialized to state.
  1161. // FIXME: 19. Restore persisted state from entry.
  1162. // 20. If hashChanged is true,
  1163. if (hash_changed) {
  1164. // then queue a global task on the DOM manipulation task source given newDocument's relevant global object
  1165. queue_global_task(Task::Source::DOMManipulation, relevant_global_object(*new_document), [new_document] {
  1166. // to fire an event named hashchange at newDocument's relevant global object,
  1167. // using HashChangeEvent, with the oldURL attribute initialized to oldURL
  1168. // and the newURL attribute initialized to newURL.
  1169. // FIXME: Implement a proper HashChangeEvent class.
  1170. auto event = DOM::Event::create(verify_cast<HTML::Window>(relevant_global_object(*new_document)).realm(), HTML::EventNames::hashchange).release_value_but_fixme_should_propagate_errors();
  1171. new_document->dispatch_event(event);
  1172. });
  1173. }
  1174. return {};
  1175. }
  1176. // https://html.spec.whatwg.org/multipage/browsers.html#allowed-to-navigate
  1177. bool BrowsingContext::is_allowed_to_navigate(BrowsingContext const& other) const
  1178. {
  1179. VERIFY(active_window());
  1180. VERIFY(active_document());
  1181. // 1. If A is not the same browsing context as B,
  1182. // and A is not one of the ancestor browsing contexts of B,
  1183. // and B is not a top-level browsing context,
  1184. // FIXME: and A's active document's active sandboxing flag set has its sandboxed navigation browsing context flag set,
  1185. // then return false.
  1186. if (this != &other
  1187. && !this->is_ancestor_of(other)
  1188. && !other.is_top_level()) {
  1189. return false;
  1190. }
  1191. // 2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, then:
  1192. if (other.is_top_level() && other.is_ancestor_of(*this)) {
  1193. // 1. If A's active window has transient activation
  1194. // and A's active document's active sandboxing flag set has its sandboxed top-level navigation with user activation browsing context flag set,
  1195. // then return false.
  1196. if (active_window()->has_transient_activation()
  1197. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedTopLevelNavigationWithUserActivation) {
  1198. return false;
  1199. }
  1200. // 2. Otherwise, if A's active window does not have transient activation
  1201. // and A's active document's active sandboxing flag set has its sandboxed top-level navigation without user activation browsing context flag set,
  1202. // then return false.
  1203. if (!active_window()->has_transient_activation()
  1204. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedTopLevelNavigationWithoutUserActivation) {
  1205. return false;
  1206. }
  1207. }
  1208. // 3. Otherwise, if B is a top-level browsing context,
  1209. // and is neither A nor one of the ancestor browsing contexts of A,
  1210. // and A's Document's active sandboxing flag set has its sandboxed navigation browsing context flag set,
  1211. // and A is not the one permitted sandboxed navigator of B,
  1212. // then return false.
  1213. if (other.is_top_level()
  1214. && &other != this
  1215. && !other.is_ancestor_of(*this)
  1216. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedNavigation
  1217. && this != other.the_one_permitted_sandboxed_navigator()) {
  1218. return false;
  1219. }
  1220. // 4. Return true.
  1221. return true;
  1222. }
  1223. // https://html.spec.whatwg.org/multipage/origin.html#one-permitted-sandboxed-navigator
  1224. BrowsingContext const* BrowsingContext::the_one_permitted_sandboxed_navigator() const
  1225. {
  1226. // FIXME: Implement this.
  1227. return nullptr;
  1228. }
  1229. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  1230. Vector<JS::Handle<DOM::Document>> BrowsingContext::document_family() const
  1231. {
  1232. HashTable<DOM::Document*> documents;
  1233. for (auto& entry : m_session_history) {
  1234. if (!entry->document)
  1235. continue;
  1236. if (documents.set(const_cast<DOM::Document*>(entry->document.ptr())) == AK::HashSetResult::ReplacedExistingEntry)
  1237. continue;
  1238. for (auto& context : entry->document->list_of_descendant_browsing_contexts()) {
  1239. for (auto& document : context->document_family()) {
  1240. documents.set(document.ptr());
  1241. }
  1242. }
  1243. }
  1244. Vector<JS::Handle<DOM::Document>> family;
  1245. for (auto* document : documents) {
  1246. family.append(*document);
  1247. }
  1248. return family;
  1249. }
  1250. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  1251. bool BrowsingContext::document_family_contains(DOM::Document const& document) const
  1252. {
  1253. return document_family().first_matching([&](auto& entry) { return entry.ptr() == &document; }).has_value();
  1254. }
  1255. VisibilityState BrowsingContext::system_visibility_state() const
  1256. {
  1257. return m_system_visibility_state;
  1258. }
  1259. // https://html.spec.whatwg.org/multipage/interaction.html#system-visibility-state
  1260. void BrowsingContext::set_system_visibility_state(VisibilityState visibility_state)
  1261. {
  1262. if (m_system_visibility_state == visibility_state)
  1263. return;
  1264. m_system_visibility_state = visibility_state;
  1265. // When a user-agent determines that the system visibility state for top-level browsing context context
  1266. // has changed to newState, it must queue a task on the user interaction task source to update
  1267. // the visibility state of all the Document objects in the top-level browsing context's document family with newState.
  1268. auto document_family = top_level_browsing_context().document_family();
  1269. // From the new navigable version, where it tells us what global object to use here:
  1270. // 1. Let document be navigable's active document.
  1271. // 2. Queue a global task on the user interaction task source given document's relevant global object to update the visibility state of document with newState.
  1272. // FIXME: Update this function to fully match the navigable version.
  1273. VERIFY(active_document());
  1274. queue_global_task(Task::Source::UserInteraction, relevant_global_object(*active_document()), [visibility_state, document_family = move(document_family)] {
  1275. for (auto& document : document_family) {
  1276. document->update_the_visibility_state(visibility_state);
  1277. }
  1278. });
  1279. }
  1280. // https://html.spec.whatwg.org/multipage/window-object.html#a-browsing-context-is-discarded
  1281. void BrowsingContext::discard()
  1282. {
  1283. m_has_been_discarded = true;
  1284. // 1. Discard all Document objects for all the entries in browsingContext's session history.
  1285. for (auto& entry : m_session_history) {
  1286. if (entry->document)
  1287. entry->document->discard();
  1288. }
  1289. // AD-HOC:
  1290. // FIXME: This should be in the session history!
  1291. if (auto* document = active_document())
  1292. document->discard();
  1293. // 2. If browsingContext is a top-level browsing context, then remove browsingContext.
  1294. if (is_top_level())
  1295. remove();
  1296. // AD-HOC:
  1297. if (parent())
  1298. parent()->remove_child(*this);
  1299. }
  1300. // https://html.spec.whatwg.org/multipage/window-object.html#close-a-browsing-context
  1301. void BrowsingContext::close()
  1302. {
  1303. VERIFY(active_document());
  1304. // FIXME: 1. If the result of calling prompt to unload with browsingContext's active document is "refuse", then return.
  1305. // 2. Unload browsingContext's active document.
  1306. active_document()->unload();
  1307. // 3. Remove browsingContext from the user interface (e.g., close or hide its tab in a tabbed browser).
  1308. if (m_page)
  1309. m_page->client().page_did_close_browsing_context(*this);
  1310. // 4. Discard browsingContext.
  1311. discard();
  1312. }
  1313. void BrowsingContext::append_child(JS::NonnullGCPtr<BrowsingContext> child)
  1314. {
  1315. VERIFY(!child->m_parent);
  1316. if (m_last_child)
  1317. m_last_child->m_next_sibling = child;
  1318. child->m_previous_sibling = m_last_child;
  1319. child->m_parent = this;
  1320. m_last_child = child;
  1321. if (!m_first_child)
  1322. m_first_child = m_last_child;
  1323. }
  1324. void BrowsingContext::remove_child(JS::NonnullGCPtr<BrowsingContext> child)
  1325. {
  1326. VERIFY(child->m_parent.ptr() == this);
  1327. if (m_first_child == child)
  1328. m_first_child = child->m_next_sibling;
  1329. if (m_last_child == child)
  1330. m_last_child = child->m_previous_sibling;
  1331. if (child->m_next_sibling)
  1332. child->m_next_sibling->m_previous_sibling = child->m_previous_sibling;
  1333. if (child->m_previous_sibling)
  1334. child->m_previous_sibling->m_next_sibling = child->m_next_sibling;
  1335. child->m_next_sibling = nullptr;
  1336. child->m_previous_sibling = nullptr;
  1337. child->m_parent = nullptr;
  1338. }
  1339. JS::GCPtr<BrowsingContext> BrowsingContext::first_child() const
  1340. {
  1341. return m_first_child;
  1342. }
  1343. JS::GCPtr<BrowsingContext> BrowsingContext::next_sibling() const
  1344. {
  1345. return m_next_sibling;
  1346. }
  1347. bool BrowsingContext::is_ancestor_of(BrowsingContext const& other) const
  1348. {
  1349. for (auto ancestor = other.parent(); ancestor; ancestor = ancestor->parent()) {
  1350. if (ancestor == this)
  1351. return true;
  1352. }
  1353. return false;
  1354. }
  1355. }