BrowsingContext.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  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.raw_username().is_empty()
  43. && url.raw_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);
  129. // - For the global object, create a new Window object.
  130. window = HTML::Window::create(realm);
  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. // 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 = HTML::HTMLDocument::create(window->realm());
  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);
  265. // - For the global object, create a new Window object.
  266. window = Window::create(realm);
  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. 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 = HTML::HTMLDocument::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 = Core::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. }).release_value_but_fixme_should_propagate_errors();
  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 && m_page->top_level_browsing_context_is_initialized() && this == &m_page->top_level_browsing_context())
  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::inform_all_viewport_clients_about_the_current_viewport_rect()
  431. {
  432. for (auto* client : m_viewport_clients)
  433. client->browsing_context_did_set_viewport_rect(viewport_rect());
  434. }
  435. void BrowsingContext::set_viewport_rect(CSSPixelRect const& rect)
  436. {
  437. bool did_change = false;
  438. if (m_size != rect.size()) {
  439. m_size = rect.size();
  440. if (auto* document = active_document()) {
  441. // NOTE: Resizing the viewport changes the reference value for viewport-relative CSS lengths.
  442. document->invalidate_style();
  443. document->set_needs_layout();
  444. }
  445. did_change = true;
  446. }
  447. if (m_viewport_scroll_offset != rect.location()) {
  448. m_viewport_scroll_offset = rect.location();
  449. scroll_offset_did_change();
  450. did_change = true;
  451. }
  452. if (did_change) {
  453. for (auto* client : m_viewport_clients)
  454. client->browsing_context_did_set_viewport_rect(rect);
  455. }
  456. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  457. HTML::main_thread_event_loop().schedule();
  458. }
  459. void BrowsingContext::set_size(CSSPixelSize size)
  460. {
  461. if (m_size == size)
  462. return;
  463. m_size = size;
  464. if (auto* document = active_document()) {
  465. document->invalidate_style();
  466. document->set_needs_layout();
  467. }
  468. for (auto* client : m_viewport_clients)
  469. client->browsing_context_did_set_viewport_rect(viewport_rect());
  470. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  471. HTML::main_thread_event_loop().schedule();
  472. }
  473. void BrowsingContext::set_needs_display()
  474. {
  475. set_needs_display(viewport_rect());
  476. }
  477. void BrowsingContext::set_needs_display(CSSPixelRect const& rect)
  478. {
  479. if (!viewport_rect().intersects(rect))
  480. return;
  481. if (is_top_level()) {
  482. if (m_page)
  483. m_page->client().page_did_invalidate(to_top_level_rect(rect));
  484. return;
  485. }
  486. if (container() && container()->layout_node())
  487. container()->layout_node()->set_needs_display();
  488. }
  489. void BrowsingContext::scroll_to(CSSPixelPoint position)
  490. {
  491. // NOTE: Scrolling to a position requires up-to-date layout *unless* we're scrolling to (0, 0)
  492. // as (0, 0) is always guaranteed to be a valid scroll position.
  493. if (!position.is_zero()) {
  494. if (active_document())
  495. active_document()->update_layout();
  496. }
  497. if (m_page && this == &m_page->top_level_browsing_context())
  498. m_page->client().page_did_request_scroll_to(position);
  499. }
  500. void BrowsingContext::scroll_to_anchor(DeprecatedString const& fragment)
  501. {
  502. JS::GCPtr<DOM::Document> document = active_document();
  503. if (!document)
  504. return;
  505. auto element = document->get_element_by_id(fragment);
  506. if (!element) {
  507. auto candidates = document->get_elements_by_name(fragment);
  508. for (auto& candidate : candidates->collect_matching_elements()) {
  509. if (is<HTML::HTMLAnchorElement>(*candidate)) {
  510. element = &verify_cast<HTML::HTMLAnchorElement>(*candidate);
  511. break;
  512. }
  513. }
  514. }
  515. if (!element)
  516. return;
  517. document->update_layout();
  518. if (!element->layout_node())
  519. return;
  520. auto& layout_node = *element->layout_node();
  521. CSSPixelRect target_rect { layout_node.box_type_agnostic_position(), { viewport_rect().width(), viewport_rect().height() } };
  522. if (is<Layout::Box>(layout_node)) {
  523. auto& layout_box = verify_cast<Layout::Box>(layout_node);
  524. auto padding_box = layout_box.box_model().padding_box();
  525. target_rect.translate_by(-padding_box.left, -padding_box.top);
  526. }
  527. if (m_page && this == &m_page->top_level_browsing_context())
  528. m_page->client().page_did_request_scroll_into_view(target_rect);
  529. }
  530. CSSPixelRect BrowsingContext::to_top_level_rect(CSSPixelRect const& a_rect)
  531. {
  532. auto rect = a_rect;
  533. rect.set_location(to_top_level_position(a_rect.location()));
  534. return rect;
  535. }
  536. CSSPixelPoint BrowsingContext::to_top_level_position(CSSPixelPoint a_position)
  537. {
  538. auto position = a_position;
  539. for (auto ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  540. if (ancestor->is_top_level())
  541. break;
  542. if (!ancestor->container())
  543. return {};
  544. if (!ancestor->container()->layout_node())
  545. return {};
  546. position.translate_by(ancestor->container()->layout_node()->box_type_agnostic_position());
  547. }
  548. return position;
  549. }
  550. void BrowsingContext::set_cursor_position(DOM::Position position)
  551. {
  552. if (m_cursor_position == position)
  553. return;
  554. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  555. m_cursor_position.node()->layout_node()->set_needs_display();
  556. m_cursor_position = move(position);
  557. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  558. m_cursor_position.node()->layout_node()->set_needs_display();
  559. reset_cursor_blink_cycle();
  560. }
  561. static DeprecatedString visible_text_in_range(DOM::Range const& range)
  562. {
  563. // NOTE: This is an adaption of Range stringification, but we skip over DOM nodes that don't have a corresponding layout node.
  564. StringBuilder builder;
  565. if (range.start_container() == range.end_container() && is<DOM::Text>(*range.start_container())) {
  566. if (!range.start_container()->layout_node())
  567. return ""sv;
  568. return static_cast<DOM::Text const&>(*range.start_container()).data().substring(range.start_offset(), range.end_offset() - range.start_offset());
  569. }
  570. if (is<DOM::Text>(*range.start_container()) && range.start_container()->layout_node())
  571. builder.append(static_cast<DOM::Text const&>(*range.start_container()).data().substring_view(range.start_offset()));
  572. for (DOM::Node const* node = range.start_container(); node != range.end_container()->next_sibling(); node = node->next_in_pre_order()) {
  573. if (is<DOM::Text>(*node) && range.contains_node(*node) && node->layout_node())
  574. builder.append(static_cast<DOM::Text const&>(*node).data());
  575. }
  576. if (is<DOM::Text>(*range.end_container()) && range.end_container()->layout_node())
  577. builder.append(static_cast<DOM::Text const&>(*range.end_container()).data().substring_view(0, range.end_offset()));
  578. return builder.to_deprecated_string();
  579. }
  580. DeprecatedString BrowsingContext::selected_text() const
  581. {
  582. auto* document = active_document();
  583. if (!document)
  584. return ""sv;
  585. auto selection = const_cast<DOM::Document&>(*document).get_selection();
  586. auto range = selection->range();
  587. if (!range)
  588. return ""sv;
  589. return visible_text_in_range(*range);
  590. }
  591. void BrowsingContext::select_all()
  592. {
  593. auto* document = active_document();
  594. if (!document)
  595. return;
  596. auto* body = document->body();
  597. if (!body)
  598. return;
  599. auto selection = document->get_selection();
  600. if (!selection)
  601. return;
  602. (void)selection->select_all_children(*document->body());
  603. }
  604. void BrowsingContext::register_viewport_client(ViewportClient& client)
  605. {
  606. auto result = m_viewport_clients.set(&client);
  607. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  608. }
  609. void BrowsingContext::unregister_viewport_client(ViewportClient& client)
  610. {
  611. bool was_removed = m_viewport_clients.remove(&client);
  612. VERIFY(was_removed);
  613. }
  614. void BrowsingContext::register_frame_nesting(AK::URL const& url)
  615. {
  616. m_frame_nesting_levels.ensure(url)++;
  617. }
  618. bool BrowsingContext::is_frame_nesting_allowed(AK::URL const& url) const
  619. {
  620. return m_frame_nesting_levels.get(url).value_or(0) < 3;
  621. }
  622. bool BrowsingContext::increment_cursor_position_offset()
  623. {
  624. if (!m_cursor_position.increment_offset())
  625. return false;
  626. reset_cursor_blink_cycle();
  627. return true;
  628. }
  629. bool BrowsingContext::decrement_cursor_position_offset()
  630. {
  631. if (!m_cursor_position.decrement_offset())
  632. return false;
  633. reset_cursor_blink_cycle();
  634. return true;
  635. }
  636. DOM::Document* BrowsingContext::container_document()
  637. {
  638. if (auto* container = this->container())
  639. return &container->document();
  640. return nullptr;
  641. }
  642. DOM::Document const* BrowsingContext::container_document() const
  643. {
  644. if (auto* container = this->container())
  645. return &container->document();
  646. return nullptr;
  647. }
  648. // https://html.spec.whatwg.org/#rendering-opportunity
  649. bool BrowsingContext::has_a_rendering_opportunity() const
  650. {
  651. // 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,
  652. // accounting for hardware refresh rate constraints and user agent throttling for performance reasons, but considering content presentable even if it's outside the viewport.
  653. // FIXME: We should at the very least say `false` here if we're an inactive browser tab.
  654. return true;
  655. }
  656. // https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-browsing-context
  657. JS::GCPtr<DOM::Node> BrowsingContext::currently_focused_area()
  658. {
  659. // 1. If topLevelBC does not have system focus, then return null.
  660. if (!is_focused_context())
  661. return nullptr;
  662. // 2. Let candidate be topLevelBC's active document.
  663. auto* candidate = active_document();
  664. // 3. While candidate's focused area is a browsing context container with a non-null nested browsing context:
  665. // set candidate to the active document of that browsing context container's nested browsing context.
  666. while (candidate->focused_element()
  667. && is<HTML::NavigableContainer>(candidate->focused_element())
  668. && static_cast<HTML::NavigableContainer&>(*candidate->focused_element()).nested_browsing_context()) {
  669. candidate = static_cast<HTML::NavigableContainer&>(*candidate->focused_element()).nested_browsing_context()->active_document();
  670. }
  671. // 4. If candidate's focused area is non-null, set candidate to candidate's focused area.
  672. if (candidate->focused_element()) {
  673. // NOTE: We return right away here instead of assigning to candidate,
  674. // since that would require compromising type safety.
  675. return candidate->focused_element();
  676. }
  677. // 5. Return candidate.
  678. return candidate;
  679. }
  680. // https://html.spec.whatwg.org/#the-rules-for-choosing-a-browsing-context-given-a-browsing-context-name
  681. BrowsingContext::ChosenBrowsingContext BrowsingContext::choose_a_browsing_context(StringView name, TokenizedFeature::NoOpener no_opener, ActivateTab activate_tab)
  682. {
  683. // The rules for choosing a browsing context, given a browsing context name name, a browsing context current, and
  684. // a boolean noopener are as follows:
  685. JS::GCPtr<AbstractBrowsingContext> matching_name_in_tree = nullptr;
  686. top_level_browsing_context().for_each_in_subtree([&](auto& context) {
  687. if (context.name() == name) {
  688. matching_name_in_tree = &context;
  689. return IterationDecision::Break;
  690. }
  691. return IterationDecision::Continue;
  692. });
  693. // 1. Let chosen be null.
  694. JS::GCPtr<AbstractBrowsingContext> chosen = nullptr;
  695. // 2. Let windowType be "existing or none".
  696. auto window_type = WindowType::ExistingOrNone;
  697. // 3. Let sandboxingFlagSet be current's active document's active sandboxing flag set.
  698. auto sandboxing_flag_set = active_document()->active_sandboxing_flag_set();
  699. // 4. If name is the empty string or an ASCII case-insensitive match for "_self", then set chosen to current.
  700. if (name.is_empty() || Infra::is_ascii_case_insensitive_match(name, "_self"sv)) {
  701. chosen = this;
  702. }
  703. // 5. Otherwise, if name is an ASCII case-insensitive match for "_parent", set chosen to current's parent browsing
  704. // context, if any, and current otherwise.
  705. else if (Infra::is_ascii_case_insensitive_match(name, "_parent"sv)) {
  706. if (auto parent = this->parent())
  707. chosen = parent;
  708. else
  709. chosen = this;
  710. }
  711. // 6. Otherwise, if name is an ASCII case-insensitive match for "_top", set chosen to current's top-level browsing
  712. // context, if any, and current otherwise.
  713. else if (Infra::is_ascii_case_insensitive_match(name, "_top"sv)) {
  714. chosen = &top_level_browsing_context();
  715. }
  716. // 7. Otherwise, if name is not an ASCII case-insensitive match for "_blank", there exists a browsing context
  717. // whose name is the same as name, current is familiar with that browsing context, and the user agent
  718. // determines that the two browsing contexts are related enough that it is ok if they reach each other,
  719. // set chosen to that browsing context. If there are multiple matching browsing contexts, the user agent
  720. // should set chosen to one in some arbitrary consistent manner, such as the most recently opened, most
  721. // recently focused, or more closely related.
  722. else if (!Infra::is_ascii_case_insensitive_match(name, "_blank"sv) && matching_name_in_tree) {
  723. chosen = matching_name_in_tree;
  724. } else {
  725. // 8. Otherwise, a new browsing context is being requested, and what happens depends on the user agent's
  726. // configuration and abilities — it is determined by the rules given for the first applicable option from
  727. // the following list:
  728. // --> If current's active window does not have transient activation and the user agent has been configured to
  729. // not show popups (i.e., the user agent has a "popup blocker" enabled)
  730. VERIFY(m_page);
  731. if (!active_window()->has_transient_activation() && m_page->should_block_pop_ups()) {
  732. // FIXME: The user agent may inform the user that a popup has been blocked.
  733. dbgln("Pop-up blocked!");
  734. }
  735. // --> If sandboxingFlagSet has the sandboxed auxiliary navigation browsing context flag set
  736. else if (sandboxing_flag_set.flags & SandboxingFlagSet::SandboxedAuxiliaryNavigation) {
  737. // FIXME: The user agent may report to a developer console that a popup has been blocked.
  738. dbgln("Pop-up blocked!");
  739. }
  740. // --> If the user agent has been configured such that in this instance it will create a new browsing context
  741. else if (true) { // FIXME: When is this the case?
  742. // 1. Set windowType to "new and unrestricted".
  743. window_type = WindowType::NewAndUnrestricted;
  744. // 2. If current's top-level browsing context's active document's cross-origin opener policy's value is
  745. // "same-origin" or "same-origin-plus-COEP", then:
  746. 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) {
  747. // 1. Let currentDocument be current's active document.
  748. auto* current_document = top_level_browsing_context().active_document();
  749. // 2. If currentDocument's origin is not same origin with currentDocument's relevant settings object's
  750. // top-level origin, then set noopener to true, name to "_blank", and windowType to "new with no opener".
  751. if (!current_document->origin().is_same_origin(current_document->relevant_settings_object().top_level_origin)) {
  752. no_opener = TokenizedFeature::NoOpener::Yes;
  753. name = "_blank"sv;
  754. window_type = WindowType::NewWithNoOpener;
  755. }
  756. }
  757. // 3. If noopener is true, then set chosen to the result of creating a new top-level browsing context.
  758. if (no_opener == TokenizedFeature::NoOpener::Yes) {
  759. auto handle = m_page->client().page_did_request_new_tab(activate_tab);
  760. chosen = RemoteBrowsingContext::create_a_new_remote_browsing_context(handle);
  761. }
  762. // 4. Otherwise:
  763. else {
  764. // 1. Set chosen to the result of creating a new auxiliary browsing context with current.
  765. // FIXME: We have no concept of auxiliary browsing context
  766. chosen = HTML::BrowsingContext::create_a_new_top_level_browsing_context(*m_page);
  767. // 2. If sandboxingFlagSet's sandboxed navigation browsing context flag is set, then current must be
  768. // set as chosen's one permitted sandboxed navigator.
  769. // FIXME: We have no concept of one permitted sandboxed navigator
  770. }
  771. // 5. If sandboxingFlagSet's sandbox propagates to auxiliary browsing contexts flag is set, then all the
  772. // flags that are set in sandboxingFlagSet must be set in chosen's popup sandboxing flag set.
  773. // FIXME: Our BrowsingContexts do not have SandboxingFlagSets yet, only documents do
  774. // 6. If name is not an ASCII case-insensitive match for "_blank", then set chosen's name to name.
  775. if (!Infra::is_ascii_case_insensitive_match(name, "_blank"sv))
  776. chosen->set_name(String::from_utf8(name).release_value_but_fixme_should_propagate_errors());
  777. }
  778. // --> If the user agent has been configured such that in this instance t will reuse current
  779. else if (false) { // FIXME: When is this the case?
  780. // Set chosen to current.
  781. chosen = *this;
  782. }
  783. // --> If the user agent has been configured such that in this instance it will not find a browsing context
  784. else if (false) { // FIXME: When is this the case?
  785. // Do nothing.
  786. }
  787. }
  788. // 9. Return chosen and windowType.
  789. return { chosen.ptr(), window_type };
  790. }
  791. // https://html.spec.whatwg.org/multipage/browsers.html#document-tree-child-browsing-context
  792. size_t BrowsingContext::document_tree_child_browsing_context_count() const
  793. {
  794. size_t count = 0;
  795. // 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.
  796. for_each_child([this, &count](BrowsingContext const& child) {
  797. if (child.is_child_of(*this) && child.container()->in_a_document_tree())
  798. ++count;
  799. });
  800. return count;
  801. }
  802. // https://html.spec.whatwg.org/multipage/browsers.html#child-browsing-context
  803. bool BrowsingContext::is_child_of(BrowsingContext const& parent) const
  804. {
  805. // A browsing context child is said to be a child browsing context of another browsing context parent,
  806. // if child's container document is non-null and child's container document's browsing context is parent.
  807. return container_document() && container_document()->browsing_context() == &parent;
  808. }
  809. // https://html.spec.whatwg.org/multipage/dom.html#still-on-its-initial-about:blank-document
  810. bool BrowsingContext::still_on_its_initial_about_blank_document() const
  811. {
  812. // A browsing context browsingContext is still on its initial about:blank Document
  813. // if browsingContext's session history's size is 1
  814. // and browsingContext's session history[0]'s document's is initial about:blank is true.
  815. return m_session_history.size() == 1
  816. && m_session_history[0]->document
  817. && m_session_history[0]->document->is_initial_about_blank();
  818. }
  819. DOM::Document const* BrowsingContext::active_document() const
  820. {
  821. auto* window = active_window();
  822. if (!window)
  823. return nullptr;
  824. return &window->associated_document();
  825. }
  826. DOM::Document* BrowsingContext::active_document()
  827. {
  828. auto* window = active_window();
  829. if (!window)
  830. return nullptr;
  831. return &window->associated_document();
  832. }
  833. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  834. HTML::Window* BrowsingContext::active_window()
  835. {
  836. return m_window_proxy->window();
  837. }
  838. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  839. HTML::Window const* BrowsingContext::active_window() const
  840. {
  841. return m_window_proxy->window();
  842. }
  843. HTML::WindowProxy* BrowsingContext::window_proxy()
  844. {
  845. return m_window_proxy.ptr();
  846. }
  847. HTML::WindowProxy const* BrowsingContext::window_proxy() const
  848. {
  849. return m_window_proxy.ptr();
  850. }
  851. void BrowsingContext::set_window_proxy(JS::GCPtr<WindowProxy> window_proxy)
  852. {
  853. m_window_proxy = move(window_proxy);
  854. }
  855. void BrowsingContext::scroll_offset_did_change()
  856. {
  857. // https://w3c.github.io/csswg-drafts/cssom-view-1/#scrolling-events
  858. // Whenever a viewport gets scrolled (whether in response to user interaction or by an API), the user agent must run these steps:
  859. // 1. Let doc be the viewport’s associated Document.
  860. auto* doc = active_document();
  861. VERIFY(doc);
  862. // 2. If doc is already in doc’s pending scroll event targets, abort these steps.
  863. for (auto& target : doc->pending_scroll_event_targets()) {
  864. if (target.ptr() == doc)
  865. return;
  866. }
  867. // 3. Append doc to doc’s pending scroll event targets.
  868. doc->pending_scroll_event_targets().append(*doc);
  869. }
  870. BrowsingContextGroup* BrowsingContext::group()
  871. {
  872. return m_group;
  873. }
  874. void BrowsingContext::set_group(BrowsingContextGroup* group)
  875. {
  876. m_group = group;
  877. }
  878. // https://html.spec.whatwg.org/multipage/browsers.html#bcg-remove
  879. void BrowsingContext::remove()
  880. {
  881. // 1. Assert: browsingContext's group is non-null, because a browsing context only gets discarded once.
  882. VERIFY(group());
  883. // 2. Let group be browsingContext's group.
  884. JS::NonnullGCPtr<BrowsingContextGroup> group = *this->group();
  885. // 3. Set browsingContext's group to null.
  886. set_group(nullptr);
  887. // 4. Remove browsingContext from group's browsing context set.
  888. group->browsing_context_set().remove(*this);
  889. // 5. If group's browsing context set is empty, then remove group from the user agent's browsing context group set.
  890. // NOTE: This is done by ~BrowsingContextGroup() when the refcount reaches 0.
  891. }
  892. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
  893. WebIDL::ExceptionOr<void> BrowsingContext::navigate(
  894. JS::NonnullGCPtr<Fetch::Infrastructure::Request> resource,
  895. BrowsingContext& source_browsing_context,
  896. bool exceptions_enabled,
  897. HistoryHandlingBehavior history_handling,
  898. Optional<PolicyContainer> history_policy_container,
  899. DeprecatedString navigation_type,
  900. Optional<String> navigation_id,
  901. Function<void(JS::NonnullGCPtr<Fetch::Infrastructure::Response>)> process_response_end_of_body)
  902. {
  903. // 1. If resource is a URL, then set resource to a new request whose URL is resource.
  904. // NOTE: This function only accepts resources that are already a request, so this is irrelevant.
  905. // 2. If resource is a request and historyHandling is "reload", then set resource's reload-navigation flag.
  906. if (history_handling == HistoryHandlingBehavior::Reload)
  907. resource->set_reload_navigation(true);
  908. // 3. If the source browsing context is not allowed to navigate browsingContext, then:
  909. if (!source_browsing_context.is_allowed_to_navigate(*this)) {
  910. // 1. If exceptionsEnabled is given and is true, then throw a "SecurityError" DOMException.
  911. if (exceptions_enabled) {
  912. VERIFY(source_browsing_context.active_document());
  913. return WebIDL::SecurityError::create(source_browsing_context.active_document()->realm(), "Source browsing context not allowed to navigate"sv);
  914. }
  915. // FIXME: 2. Otherwise, the user agent may instead offer to open resource in a new top-level browsing context
  916. // or in the top-level browsing context of the source browsing context, at the user's option,
  917. // in which case the user agent must navigate that designated top-level browsing context
  918. // to resource as if the user had requested it independently.
  919. }
  920. // 4. If navigationId is null:
  921. if (!navigation_id.has_value()) {
  922. // 1. If historyHandling is "reload", and browsingContext's active document's navigation id is not null,
  923. if (history_handling == HistoryHandlingBehavior::Reload && active_document()->navigation_id().has_value()) {
  924. // let navigationId be browsingContext's active document's navigation id.
  925. navigation_id = active_document()->navigation_id();
  926. } else {
  927. // Otherwise let navigation id be the result of generating a random UUID. [UUID]
  928. // FIXME: Generate a UUID.
  929. navigation_id = "FIXME"_string;
  930. }
  931. }
  932. // FIXME: 5. If browsingContext's active document's unload counter is greater than 0,
  933. // then invoke WebDriver BiDi navigation failed
  934. // with a WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is resource's url
  935. // and return.
  936. // 6. If historyHandling is "default", and any of the following are true:
  937. // - browsingContext is still on its initial about:blank Document
  938. // - resource is a request whose URL equals browsingContext's active document's URL
  939. // - resource is a request whose URL's scheme is "javascript"
  940. if (history_handling == HistoryHandlingBehavior::Default
  941. && (still_on_its_initial_about_blank_document()
  942. || resource->url().equals(active_document()->url())
  943. || resource->url().scheme() == "javascript"sv)) {
  944. // then set historyHandling to "replace".
  945. history_handling = HistoryHandlingBehavior::Replace;
  946. }
  947. // 7. If historyHandling is not "reload", resource is a request,
  948. // resource's URL equals browsingContext's active document's URL with exclude fragments set to true,
  949. // and resource's URL's fragment is non-null, then:
  950. if (history_handling != HistoryHandlingBehavior::Reload
  951. && resource->url().equals(active_document()->url(), AK::URL::ExcludeFragment::Yes)
  952. && resource->url().fragment().has_value()) {
  953. // 1. Navigate to a fragment given browsingContext, resource's URL, historyHandling, and navigationId.
  954. TRY(navigate_to_a_fragment(resource->url(), history_handling, *navigation_id));
  955. // 2. Return.
  956. return {};
  957. }
  958. // FIXME: 8. Let incumbentNavigationOrigin be the origin of the incumbent settings object,
  959. // or if no script was involved, the origin of the node document of the element that initiated the navigation.
  960. // FIXME: 9. Let initiatorPolicyContainer be a clone of the source browsing context's active document's policy container.
  961. // FIXME: 10. If resource is a request, then set resource's policy container to initiatorPolicyContainer.
  962. // FIXME: 11. Cancel any preexisting but not yet mature attempt to navigate browsingContext,
  963. // including canceling any instances of the fetch algorithm started by those attempts.
  964. // If one of those attempts has already created and initialized a new Document object,
  965. // abort that Document also.
  966. // (Navigation attempts that have matured already have session history entries,
  967. // and are therefore handled during the update the session history with the new page algorithm, later.)
  968. // FIXME: 12. Let unloadPromptResult be the result of calling prompt to unload with the active document of browsingContext.
  969. // If this instance of the navigation algorithm gets canceled while this step is running,
  970. // the prompt to unload algorithm must nonetheless be run to completion.
  971. // FIXME: 13. If unloadPromptResult is "refuse", then return a new WebDriver BiDi navigation status whose id is navigationId and status is "canceled".
  972. // 14. Abort the active document of browsingContext.
  973. active_document()->abort();
  974. // FIXME: 15. If browsingContext is a child browsing context, then put it in the delaying load events mode.
  975. // The user agent must take this child browsing context out of the delaying load events mode when this navigation algorithm later matures,
  976. // or when it terminates (whether due to having run all the steps, or being canceled, or being aborted),
  977. // whichever happens first.
  978. // FIXME: 16. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and browsingContext's container.
  979. // FIXME: 17. Let allowedToDownload be the result of running the allowed to download algorithm given the source browsing context and browsingContext.
  980. // 18. Let hasTransientActivation be true if the source browsing context's active window has transient activation; otherwise false.
  981. [[maybe_unused]] bool has_transient_activation = source_browsing_context.active_window()->has_transient_activation();
  982. // 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".
  983. // 20. Return, and continue running these steps in parallel.
  984. // FIXME: Implement the rest of this algorithm
  985. (void)history_policy_container;
  986. (void)navigation_type;
  987. (void)process_response_end_of_body;
  988. // AD-HOC:
  989. auto request = LoadRequest::create_for_url_on_page(resource->url(), page());
  990. request.set_method(DeprecatedString { resource->method() });
  991. for (auto& header : *resource->header_list()) {
  992. request.set_header(DeprecatedString { header.name.bytes() }, DeprecatedString { header.value.bytes() });
  993. }
  994. if (request.method() == "POST"sv) {
  995. if (resource->body().has<ByteBuffer>()) {
  996. auto const& byte_buffer = resource->body().get<ByteBuffer>();
  997. request.set_body(byte_buffer);
  998. request.set_header("Content-Length", DeprecatedString::number(byte_buffer.size()));
  999. } else {
  1000. request.set_header("Content-Length", DeprecatedString::number(0));
  1001. }
  1002. }
  1003. loader().load(request, FrameLoader::Type::Navigation);
  1004. return {};
  1005. }
  1006. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate-fragid
  1007. WebIDL::ExceptionOr<void> BrowsingContext::navigate_to_a_fragment(AK::URL const& url, HistoryHandlingBehavior history_handling, String navigation_id)
  1008. {
  1009. // 1. If historyHandling is not "replace",
  1010. if (history_handling != HistoryHandlingBehavior::Replace) {
  1011. // FIXME: then remove all the entries in browsingContext's session history after the current entry.
  1012. // (If the current entry is the last entry in the session history, then no entries are removed.)
  1013. }
  1014. // 2. Remove any tasks queued by the history traversal task source that are associated with any Document objects
  1015. // in browsingContext's top-level browsing context's document family.
  1016. HTML::main_thread_event_loop().task_queue().remove_tasks_matching([&](HTML::Task const& task) {
  1017. return task.source() == Task::Source::HistoryTraversal
  1018. && task.document()
  1019. && top_level_browsing_context().document_family_contains(*task.document());
  1020. });
  1021. // 3. Append a new session history entry to the session history whose URL is url,
  1022. // document is the current entry's document,
  1023. // policy container is the current entry's policy-container
  1024. // and scroll restoration mode is the current entry's scroll restoration mode.
  1025. auto new_entry = heap().allocate_without_realm<SessionHistoryEntry>();
  1026. new_entry->url = url;
  1027. new_entry->document = current_entry().document;
  1028. new_entry->serialized_state = {};
  1029. new_entry->policy_container = current_entry().policy_container;
  1030. new_entry->scroll_restoration_mode = current_entry().scroll_restoration_mode;
  1031. new_entry->browsing_context_name = {};
  1032. new_entry->original_source_browsing_context = {};
  1033. m_session_history.append(*new_entry);
  1034. // 4. Traverse the history to the new entry, with historyHandling set to historyHandling.
  1035. // This will scroll to the fragment given in what is now the document's URL.
  1036. TRY(traverse_the_history(m_session_history.size() - 1, history_handling));
  1037. // FIXME: 5. Invoke WebDriver BiDi fragment navigated with browsingContext,
  1038. // and a new WebDriver BiDi navigation status whose id is navigationId, url is resource's url, and status is "complete".
  1039. (void)navigation_id;
  1040. return {};
  1041. }
  1042. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#traverse-the-history
  1043. WebIDL::ExceptionOr<void> BrowsingContext::traverse_the_history(size_t entry_index, HistoryHandlingBehavior history_handling, bool explicit_history_navigation)
  1044. {
  1045. auto entry = m_session_history[entry_index];
  1046. // 1. If entry's document is null, then:
  1047. if (!entry->document) {
  1048. // 1. Assert: historyHandling is "default".
  1049. VERIFY(history_handling == HistoryHandlingBehavior::Default);
  1050. // 2. Let request be a new request whose URL is entry's URL.
  1051. auto& vm = Bindings::main_thread_vm();
  1052. auto request = Fetch::Infrastructure::Request::create(vm);
  1053. request->set_url(entry->url);
  1054. // 3. If explicitHistoryNavigation is true, then set request's history-navigation flag.
  1055. if (explicit_history_navigation)
  1056. request->set_history_navigation(true);
  1057. // 4. Navigate the browsing context to request with historyHandling set to "entry update"
  1058. // and with historyPolicyContainer set to entry's policy container.
  1059. // The navigation must be done using the same source browsing context as was used the first time entry was created.
  1060. VERIFY(entry->original_source_browsing_context);
  1061. TRY(navigate(request, *entry->original_source_browsing_context, false, HistoryHandlingBehavior::EntryUpdate, entry->policy_container));
  1062. // 5. Return.
  1063. return {};
  1064. }
  1065. // FIXME: 2. Save persisted state to the current entry.
  1066. // 3. Let newDocument be entry's document.
  1067. JS::GCPtr<DOM::Document> new_document = entry->document.ptr();
  1068. // 4. Assert: newDocument's is initial about:blank is false,
  1069. // i.e., we never traverse back to the initial about:blank Document because it always gets replaced when we navigate away from it.
  1070. VERIFY(!new_document->is_initial_about_blank());
  1071. // 5. If newDocument is different than the current entry's document, or historyHandling is "entry update" or "reload", then:
  1072. if (new_document.ptr() != current_entry().document.ptr()
  1073. || history_handling == HistoryHandlingBehavior::EntryUpdate) {
  1074. // FIXME: 1. If newDocument's suspended timer handles is not empty:
  1075. // FIXME: 1. Assert: newDocument's suspension time is not zero.
  1076. // FIXME: 2. Let suspendDuration be the current high resolution time minus newDocument's suspension time.
  1077. // FIXME: 3. Let activeTimers be newDocument's relevant global object's map of active timers.
  1078. // FIXME: 4. For each handle in newDocument's suspended timer handles, if activeTimers[handle] exists, then increase activeTimers[handle] by suspendDuration.
  1079. }
  1080. // 2. Remove any tasks queued by the history traversal task source
  1081. // that are associated with any Document objects in the top-level browsing context's document family.
  1082. HTML::main_thread_event_loop().task_queue().remove_tasks_matching([&](HTML::Task const& task) {
  1083. return task.source() == Task::Source::HistoryTraversal
  1084. && task.document()
  1085. && top_level_browsing_context().document_family_contains(*task.document());
  1086. });
  1087. // 3. If newDocument's origin is not same origin with the current entry's document's origin, then:
  1088. if (!new_document->origin().is_same_origin(current_entry().document->origin())) {
  1089. // FIXME: 1. Let entriesToUpdate be all entries in the session history whose document's origin is same origin as the active document
  1090. // and that are contiguous with the current entry.
  1091. // FIXME: 2. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to the current browsing context name.
  1092. // 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.
  1093. }
  1094. // 4. Set the active document of the browsing context to newDocument.
  1095. set_active_document(*new_document);
  1096. // 5. If entry's browsing context name is not null, then:
  1097. if (entry->browsing_context_name.has_value()) {
  1098. // 1. Set the browsing context's name to entry's browsing context name.
  1099. m_name = *entry->browsing_context_name;
  1100. // 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.
  1101. // FIXME: 3. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to null.
  1102. }
  1103. // FIXME: 6. If newDocument has any form controls whose autofill field name is "off", invoke the reset algorithm of each of those elements.
  1104. // 7. If newDocument's current document readiness "complete",
  1105. if (new_document->ready_state() == "complete"sv) {
  1106. // then queue a global task on the DOM manipulation task source given newDocument's relevant global object to run the following steps:
  1107. queue_global_task(Task::Source::DOMManipulation, relevant_global_object(*new_document), [new_document] {
  1108. // 1. If newDocument's page showing flag is true, then abort these steps.
  1109. if (new_document->page_showing())
  1110. return;
  1111. // 2. Set newDocument's page showing flag to true.
  1112. new_document->set_page_showing(true);
  1113. // 3. Update the visibility state of newDocument to "hidden".
  1114. new_document->update_the_visibility_state(VisibilityState::Hidden);
  1115. // 4. Fire a page transition event named pageshow at newDocument's relevant global object with true.
  1116. auto& window = verify_cast<HTML::Window>(relevant_global_object(*new_document));
  1117. window.fire_a_page_transition_event(HTML::EventNames::pageshow, true);
  1118. });
  1119. }
  1120. // 6. Set newDocument's URL to entry's URL.
  1121. new_document->set_url(entry->url);
  1122. // 7. Let hashChanged be false, and let oldURL and newURL be null.
  1123. bool hash_changed = false;
  1124. Optional<AK::URL> old_url;
  1125. Optional<AK::URL> new_url;
  1126. // 8. If entry's URL's fragment is not identical to the current entry's URL's fragment,
  1127. // and entry's document equals the current entry's document,
  1128. if (entry->url.fragment() != current_entry().url.fragment()
  1129. && entry->document.ptr() == current_entry().document.ptr()) {
  1130. // then set hashChanged to true, set oldURL to the current entry's URL, and set newURL to entry's URL.
  1131. hash_changed = true;
  1132. old_url = current_entry().url;
  1133. new_url = entry->url;
  1134. }
  1135. // 9. If historyHandling is "replace", then remove the entry immediately before entry in the session history.
  1136. if (history_handling == HistoryHandlingBehavior::Replace) {
  1137. // FIXME: This is gnarly.
  1138. m_session_history.remove(entry_index - 1);
  1139. entry_index--;
  1140. entry = m_session_history[entry_index];
  1141. }
  1142. // 10. If entry's persisted user state is null, and its URL's fragment is non-null, then scroll to the fragment.
  1143. if (entry->url.fragment().has_value())
  1144. active_document()->scroll_to_the_fragment();
  1145. // 11. Set the current entry to entry.
  1146. m_session_history_index = entry_index;
  1147. // 12. Let targetRealm be the current Realm Record.
  1148. auto* target_realm = Bindings::main_thread_vm().current_realm();
  1149. VERIFY(target_realm);
  1150. // FIXME: 13. Let state be null.
  1151. // FIXME: 14. If entry's serialized state is not null, then set state to StructuredDeserialize(entry's serialized state, targetRealm).
  1152. // If this throws an exception, catch it and ignore the exception.
  1153. // FIXME: 15. Set newDocument's History object's state to state.
  1154. // FIXME: 16. Let stateChanged be true if newDocument has a latest entry, and that entry is not entry; otherwise let it be false.
  1155. // FIXME: 17. Set newDocument's latest entry to entry.
  1156. // 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.
  1157. // FIXME: 19. Restore persisted state from entry.
  1158. // 20. If hashChanged is true,
  1159. if (hash_changed) {
  1160. // then queue a global task on the DOM manipulation task source given newDocument's relevant global object
  1161. queue_global_task(Task::Source::DOMManipulation, relevant_global_object(*new_document), [new_document] {
  1162. // to fire an event named hashchange at newDocument's relevant global object,
  1163. // using HashChangeEvent, with the oldURL attribute initialized to oldURL
  1164. // and the newURL attribute initialized to newURL.
  1165. // FIXME: Implement a proper HashChangeEvent class.
  1166. auto event = DOM::Event::create(verify_cast<HTML::Window>(relevant_global_object(*new_document)).realm(), HTML::EventNames::hashchange);
  1167. new_document->dispatch_event(event);
  1168. });
  1169. }
  1170. return {};
  1171. }
  1172. // https://html.spec.whatwg.org/multipage/browsers.html#allowed-to-navigate
  1173. bool BrowsingContext::is_allowed_to_navigate(BrowsingContext const& other) const
  1174. {
  1175. VERIFY(active_window());
  1176. VERIFY(active_document());
  1177. // 1. If A is not the same browsing context as B,
  1178. // and A is not one of the ancestor browsing contexts of B,
  1179. // and B is not a top-level browsing context,
  1180. // FIXME: and A's active document's active sandboxing flag set has its sandboxed navigation browsing context flag set,
  1181. // then return false.
  1182. if (this != &other
  1183. && !this->is_ancestor_of(other)
  1184. && !other.is_top_level()) {
  1185. return false;
  1186. }
  1187. // 2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, then:
  1188. if (other.is_top_level() && other.is_ancestor_of(*this)) {
  1189. // 1. If A's active window has transient activation
  1190. // and A's active document's active sandboxing flag set has its sandboxed top-level navigation with user activation browsing context flag set,
  1191. // then return false.
  1192. if (active_window()->has_transient_activation()
  1193. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedTopLevelNavigationWithUserActivation) {
  1194. return false;
  1195. }
  1196. // 2. Otherwise, if A's active window does not have transient activation
  1197. // and A's active document's active sandboxing flag set has its sandboxed top-level navigation without user activation browsing context flag set,
  1198. // then return false.
  1199. if (!active_window()->has_transient_activation()
  1200. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedTopLevelNavigationWithoutUserActivation) {
  1201. return false;
  1202. }
  1203. }
  1204. // 3. Otherwise, if B is a top-level browsing context,
  1205. // and is neither A nor one of the ancestor browsing contexts of A,
  1206. // and A's Document's active sandboxing flag set has its sandboxed navigation browsing context flag set,
  1207. // and A is not the one permitted sandboxed navigator of B,
  1208. // then return false.
  1209. if (other.is_top_level()
  1210. && &other != this
  1211. && !other.is_ancestor_of(*this)
  1212. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedNavigation
  1213. && this != other.the_one_permitted_sandboxed_navigator()) {
  1214. return false;
  1215. }
  1216. // 4. Return true.
  1217. return true;
  1218. }
  1219. // https://html.spec.whatwg.org/multipage/origin.html#one-permitted-sandboxed-navigator
  1220. BrowsingContext const* BrowsingContext::the_one_permitted_sandboxed_navigator() const
  1221. {
  1222. // FIXME: Implement this.
  1223. return nullptr;
  1224. }
  1225. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  1226. Vector<JS::Handle<DOM::Document>> BrowsingContext::document_family() const
  1227. {
  1228. HashTable<DOM::Document*> documents;
  1229. for (auto& entry : m_session_history) {
  1230. if (!entry->document)
  1231. continue;
  1232. if (documents.set(const_cast<DOM::Document*>(entry->document.ptr())) == AK::HashSetResult::ReplacedExistingEntry)
  1233. continue;
  1234. for (auto& context : entry->document->list_of_descendant_browsing_contexts()) {
  1235. for (auto& document : context->document_family()) {
  1236. documents.set(document.ptr());
  1237. }
  1238. }
  1239. }
  1240. Vector<JS::Handle<DOM::Document>> family;
  1241. for (auto* document : documents) {
  1242. family.append(*document);
  1243. }
  1244. return family;
  1245. }
  1246. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  1247. bool BrowsingContext::document_family_contains(DOM::Document const& document) const
  1248. {
  1249. return document_family().first_matching([&](auto& entry) { return entry.ptr() == &document; }).has_value();
  1250. }
  1251. VisibilityState BrowsingContext::system_visibility_state() const
  1252. {
  1253. return m_system_visibility_state;
  1254. }
  1255. // https://html.spec.whatwg.org/multipage/interaction.html#system-visibility-state
  1256. void BrowsingContext::set_system_visibility_state(VisibilityState visibility_state)
  1257. {
  1258. if (m_system_visibility_state == visibility_state)
  1259. return;
  1260. m_system_visibility_state = visibility_state;
  1261. // When a user-agent determines that the system visibility state for top-level browsing context context
  1262. // has changed to newState, it must queue a task on the user interaction task source to update
  1263. // the visibility state of all the Document objects in the top-level browsing context's document family with newState.
  1264. auto document_family = top_level_browsing_context().document_family();
  1265. // From the new navigable version, where it tells us what global object to use here:
  1266. // 1. Let document be navigable's active document.
  1267. // 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.
  1268. // FIXME: Update this function to fully match the navigable version.
  1269. VERIFY(active_document());
  1270. queue_global_task(Task::Source::UserInteraction, relevant_global_object(*active_document()), [visibility_state, document_family = move(document_family)] {
  1271. for (auto& document : document_family) {
  1272. document->update_the_visibility_state(visibility_state);
  1273. }
  1274. });
  1275. }
  1276. // https://html.spec.whatwg.org/multipage/window-object.html#a-browsing-context-is-discarded
  1277. void BrowsingContext::discard()
  1278. {
  1279. m_has_been_discarded = true;
  1280. // 1. Discard all Document objects for all the entries in browsingContext's session history.
  1281. for (auto& entry : m_session_history) {
  1282. if (entry->document)
  1283. entry->document->discard();
  1284. }
  1285. // AD-HOC:
  1286. // FIXME: This should be in the session history!
  1287. if (auto* document = active_document())
  1288. document->discard();
  1289. // 2. If browsingContext is a top-level browsing context, then remove browsingContext.
  1290. if (is_top_level())
  1291. remove();
  1292. // AD-HOC:
  1293. if (parent())
  1294. parent()->remove_child(*this);
  1295. }
  1296. // https://html.spec.whatwg.org/multipage/window-object.html#close-a-browsing-context
  1297. void BrowsingContext::close()
  1298. {
  1299. VERIFY(active_document());
  1300. // FIXME: 1. If the result of calling prompt to unload with browsingContext's active document is "refuse", then return.
  1301. // 2. Unload browsingContext's active document.
  1302. active_document()->unload();
  1303. // 3. Remove browsingContext from the user interface (e.g., close or hide its tab in a tabbed browser).
  1304. if (m_page)
  1305. m_page->client().page_did_close_browsing_context(*this);
  1306. // 4. Discard browsingContext.
  1307. discard();
  1308. }
  1309. void BrowsingContext::append_child(JS::NonnullGCPtr<BrowsingContext> child)
  1310. {
  1311. VERIFY(!child->m_parent);
  1312. if (m_last_child)
  1313. m_last_child->m_next_sibling = child;
  1314. child->m_previous_sibling = m_last_child;
  1315. child->m_parent = this;
  1316. m_last_child = child;
  1317. if (!m_first_child)
  1318. m_first_child = m_last_child;
  1319. }
  1320. void BrowsingContext::remove_child(JS::NonnullGCPtr<BrowsingContext> child)
  1321. {
  1322. VERIFY(child->m_parent.ptr() == this);
  1323. if (m_first_child == child)
  1324. m_first_child = child->m_next_sibling;
  1325. if (m_last_child == child)
  1326. m_last_child = child->m_previous_sibling;
  1327. if (child->m_next_sibling)
  1328. child->m_next_sibling->m_previous_sibling = child->m_previous_sibling;
  1329. if (child->m_previous_sibling)
  1330. child->m_previous_sibling->m_next_sibling = child->m_next_sibling;
  1331. child->m_next_sibling = nullptr;
  1332. child->m_previous_sibling = nullptr;
  1333. child->m_parent = nullptr;
  1334. }
  1335. JS::GCPtr<BrowsingContext> BrowsingContext::first_child() const
  1336. {
  1337. return m_first_child;
  1338. }
  1339. JS::GCPtr<BrowsingContext> BrowsingContext::next_sibling() const
  1340. {
  1341. return m_next_sibling;
  1342. }
  1343. bool BrowsingContext::is_ancestor_of(BrowsingContext const& other) const
  1344. {
  1345. for (auto ancestor = other.parent(); ancestor; ancestor = ancestor->parent()) {
  1346. if (ancestor == this)
  1347. return true;
  1348. }
  1349. return false;
  1350. }
  1351. }