BrowsingContext.cpp 73 KB

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