BrowsingContext.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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/DocumentState.h>
  17. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  18. #include <LibWeb/HTML/HTMLAnchorElement.h>
  19. #include <LibWeb/HTML/HTMLDocument.h>
  20. #include <LibWeb/HTML/HTMLInputElement.h>
  21. #include <LibWeb/HTML/NavigableContainer.h>
  22. #include <LibWeb/HTML/RemoteBrowsingContext.h>
  23. #include <LibWeb/HTML/SandboxingFlagSet.h>
  24. #include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
  25. #include <LibWeb/HTML/TraversableNavigable.h>
  26. #include <LibWeb/HTML/Window.h>
  27. #include <LibWeb/HTML/WindowProxy.h>
  28. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  29. #include <LibWeb/Infra/Strings.h>
  30. #include <LibWeb/Layout/BreakNode.h>
  31. #include <LibWeb/Layout/TextNode.h>
  32. #include <LibWeb/Layout/Viewport.h>
  33. #include <LibWeb/Namespace.h>
  34. #include <LibWeb/Page/Page.h>
  35. #include <LibWeb/URL/URL.h>
  36. namespace Web::HTML {
  37. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#matches-about:blank
  38. bool url_matches_about_blank(AK::URL const& url)
  39. {
  40. // 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.
  41. return url.scheme() == "about"sv
  42. && url.serialize_path() == "blank"sv
  43. && url.raw_username().is_empty()
  44. && url.raw_password().is_empty()
  45. && url.host().has<Empty>();
  46. }
  47. // FIXME: This is an outdated older version of "determining the origin" and should be removed.
  48. // https://html.spec.whatwg.org/multipage/browsers.html#determining-the-origin
  49. HTML::Origin determine_the_origin(BrowsingContext const& browsing_context, Optional<AK::URL> url, SandboxingFlagSet sandbox_flags, Optional<HTML::Origin> invocation_origin)
  50. {
  51. // 1. If sandboxFlags has its sandboxed origin browsing context flag set, then return a new opaque origin.
  52. if (has_flag(sandbox_flags, SandboxingFlagSet::SandboxedOrigin)) {
  53. return HTML::Origin {};
  54. }
  55. // 2. If url is null, then return a new opaque origin.
  56. if (!url.has_value()) {
  57. return HTML::Origin {};
  58. }
  59. // 3. If invocationOrigin is non-null and url matches about:blank, then return invocationOrigin.
  60. if (invocation_origin.has_value() && url_matches_about_blank(*url)) {
  61. return invocation_origin.value();
  62. }
  63. // 4. If url is about:srcdoc, then return the origin of browsingContext's container document.
  64. if (url == AK::URL("about:srcdoc")) {
  65. VERIFY(browsing_context.container_document());
  66. return browsing_context.container_document()->origin();
  67. }
  68. // 5. Return url's origin.
  69. return URL::url_origin(*url);
  70. }
  71. // https://html.spec.whatwg.org/multipage/document-sequences.html#determining-the-origin
  72. HTML::Origin determine_the_origin(AK::URL const& url, SandboxingFlagSet sandbox_flags, Optional<HTML::Origin> source_origin, Optional<HTML::Origin> container_origin)
  73. {
  74. // 1. If sandboxFlags has its sandboxed origin browsing context flag set, then return a new opaque origin.
  75. if (has_flag(sandbox_flags, SandboxingFlagSet::SandboxedOrigin)) {
  76. return HTML::Origin {};
  77. }
  78. // FIXME: 2. If url is null, then return a new opaque origin.
  79. // FIXME: There appears to be no way to get a null URL here, so it might be a spec bug.
  80. // 3. If url is about:srcdoc, then:
  81. if (url == "about:srcdoc"sv) {
  82. // 1. Assert: containerOrigin is non-null.
  83. VERIFY(container_origin.has_value());
  84. // 2. Return containerOrigin.
  85. return container_origin.release_value();
  86. }
  87. // 4. If url matches about:blank and sourceOrigin is non-null, then return sourceOrigin.
  88. if (url_matches_about_blank(url) && source_origin.has_value())
  89. return source_origin.release_value();
  90. // 5. Return url's origin.
  91. return URL::url_origin(url);
  92. }
  93. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-auxiliary-browsing-context
  94. WebIDL::ExceptionOr<BrowsingContext::BrowsingContextAndDocument> BrowsingContext::create_a_new_auxiliary_browsing_context_and_document(Page& page, JS::NonnullGCPtr<HTML::BrowsingContext> opener)
  95. {
  96. // 1. Let openerTopLevelBrowsingContext be opener's top-level traversable's active browsing context.
  97. auto opener_top_level_browsing_context = opener->top_level_traversable()->active_browsing_context();
  98. // 2. Let group be openerTopLevelBrowsingContext's group.
  99. auto group = opener_top_level_browsing_context->group();
  100. // 3. Assert: group is non-null, as navigating invokes this directly.
  101. VERIFY(group);
  102. // 4. Set browsingContext and document be the result of creating a new browsing context and document with opener's active document, null, and group.
  103. auto [browsing_context, document] = TRY(create_a_new_browsing_context_and_document(page, opener->active_document(), nullptr, *group));
  104. // FIXME: 5. Set browsingContext's is auxiliary to true.
  105. // 6. Append browsingContext to group.
  106. group->append(browsing_context);
  107. // 7. Set browsingContext's opener browsing context to opener.
  108. browsing_context->set_opener_browsing_context(opener);
  109. // FIXME: 8. Set browsingContext's virtual browsing context group ID to openerTopLevelBrowsingContext's virtual browsing context group ID.
  110. // FIXME: 9. Set browsingContext's opener origin at creation to opener's active document's origin.
  111. // 10. Return browsingContext and document.
  112. return BrowsingContext::BrowsingContextAndDocument { browsing_context, document };
  113. }
  114. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-browsing-context
  115. 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)
  116. {
  117. auto& vm = group->vm();
  118. // 1. Let browsingContext be a new browsing context.
  119. JS::NonnullGCPtr<BrowsingContext> browsing_context = *vm.heap().allocate_without_realm<BrowsingContext>(page, nullptr);
  120. // 2. Let unsafeContextCreationTime be the unsafe shared current time.
  121. [[maybe_unused]] auto unsafe_context_creation_time = HighResolutionTime::unsafe_shared_current_time();
  122. // 3. Let creatorOrigin be null.
  123. Optional<Origin> creator_origin = {};
  124. // 4. If creator is non-null, then:
  125. if (creator) {
  126. // 1. Set creatorOrigin to creator's origin.
  127. creator_origin = creator->origin();
  128. // FIXME: 2. Set browsingContext's creator base URL to an algorithm which returns creator's base URL.
  129. // 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.
  130. }
  131. // FIXME: 5. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and embedder.
  132. SandboxingFlagSet sandbox_flags = {};
  133. // 6. Let origin be the result of determining the origin given about:blank, sandboxFlags, creatorOrigin, and null.
  134. auto origin = determine_the_origin(AK::URL("about:blank"sv), sandbox_flags, creator_origin, {});
  135. // FIXME: 7. Let permissionsPolicy be the result of creating a permissions policy given browsingContext and origin. [PERMISSIONSPOLICY]
  136. // FIXME: 8. Let agent be the result of obtaining a similar-origin window agent given origin, group, and false.
  137. JS::GCPtr<Window> window;
  138. // 9. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
  139. auto realm_execution_context = Bindings::create_a_new_javascript_realm(
  140. Bindings::main_thread_vm(),
  141. [&](JS::Realm& realm) -> JS::Object* {
  142. auto window_proxy = realm.heap().allocate<WindowProxy>(realm, realm);
  143. browsing_context->set_window_proxy(window_proxy);
  144. // - For the global object, create a new Window object.
  145. window = Window::create(realm);
  146. return window.ptr();
  147. },
  148. [&](JS::Realm&) -> JS::Object* {
  149. // - For the global this binding, use browsingContext's WindowProxy object.
  150. return browsing_context->window_proxy();
  151. });
  152. // 10. Let topLevelCreationURL be about:blank if embedder is null; otherwise embedder's relevant settings object's top-level creation URL.
  153. auto top_level_creation_url = !embedder ? AK::URL("about:blank") : relevant_settings_object(*embedder).top_level_creation_url;
  154. // 11. Let topLevelOrigin be origin if embedder is null; otherwise embedder's relevant settings object's top-level origin.
  155. auto top_level_origin = !embedder ? origin : relevant_settings_object(*embedder).origin();
  156. // 12. Set up a window environment settings object with about:blank, realm execution context, null, topLevelCreationURL, and topLevelOrigin.
  157. WindowEnvironmentSettingsObject::setup(
  158. AK::URL("about:blank"),
  159. move(realm_execution_context),
  160. {},
  161. top_level_creation_url,
  162. top_level_origin);
  163. // 13. Let loadTimingInfo be a new document load timing info with its navigation start time set to the result of calling
  164. // coarsen time with unsafeContextCreationTime and the new environment settings object's cross-origin isolated capability.
  165. auto load_timing_info = DOM::DocumentLoadTimingInfo();
  166. load_timing_info.navigation_start_time = HighResolutionTime::coarsen_time(
  167. unsafe_context_creation_time,
  168. verify_cast<WindowEnvironmentSettingsObject>(Bindings::host_defined_environment_settings_object(window->realm())).cross_origin_isolated_capability() == CanUseCrossOriginIsolatedAPIs::Yes);
  169. // 14. Let document be a new Document, with:
  170. auto document = HTML::HTMLDocument::create(window->realm());
  171. // Non-standard
  172. window->set_associated_document(*document);
  173. // type: "html"
  174. document->set_document_type(DOM::Document::Type::HTML);
  175. // content type: "text/html"
  176. document->set_content_type("text/html"_string);
  177. // mode: "quirks"
  178. document->set_quirks_mode(DOM::QuirksMode::Yes);
  179. // origin: origin
  180. document->set_origin(origin);
  181. // browsing context: browsingContext
  182. document->set_browsing_context(browsing_context);
  183. // FIXME: permissions policy: permissionsPolicy
  184. // FIXME: active sandboxing flag set: sandboxFlags
  185. // load timing info: loadTimingInfo
  186. document->set_load_timing_info(load_timing_info);
  187. // is initial about:blank: true
  188. document->set_is_initial_about_blank(true);
  189. // 15. If creator is non-null, then:
  190. if (creator) {
  191. // 1. Set document's referrer to the serialization of creator's URL.
  192. document->set_referrer(creator->url().serialize());
  193. // FIXME: 2. Set document's policy container to a clone of creator's policy container.
  194. // 3. If creator's origin is same origin with creator's relevant settings object's top-level origin,
  195. if (creator->origin().is_same_origin(creator->relevant_settings_object().top_level_origin)) {
  196. // 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.
  197. VERIFY(creator->browsing_context());
  198. VERIFY(creator->browsing_context()->top_level_browsing_context()->active_document());
  199. document->set_cross_origin_opener_policy(creator->browsing_context()->top_level_browsing_context()->active_document()->cross_origin_opener_policy());
  200. }
  201. }
  202. // 16. Assert: document's URL and document's relevant settings object's creation URL are about:blank.
  203. VERIFY(document->url() == "about:blank"sv);
  204. VERIFY(document->relevant_settings_object().creation_url == "about:blank"sv);
  205. // 17. Mark document as ready for post-load tasks.
  206. document->set_ready_for_post_load_tasks(true);
  207. // 18. Ensure that document has a single child html node, which itself has two empty child nodes: a head element, and a body element.
  208. auto html_node = TRY(DOM::create_element(document, HTML::TagNames::html, Namespace::HTML));
  209. auto head_element = TRY(DOM::create_element(document, HTML::TagNames::head, Namespace::HTML));
  210. TRY(html_node->append_child(head_element));
  211. auto body_element = TRY(DOM::create_element(document, HTML::TagNames::body, Namespace::HTML));
  212. TRY(html_node->append_child(body_element));
  213. TRY(document->append_child(html_node));
  214. // 19. Make active document.
  215. document->make_active();
  216. // 20. Completely finish loading document.
  217. document->completely_finish_loading();
  218. // 21. Return browsingContext and document.
  219. return BrowsingContext::BrowsingContextAndDocument { browsing_context, document };
  220. }
  221. BrowsingContext::BrowsingContext(Page& page, HTML::NavigableContainer* container)
  222. : m_page(page)
  223. , m_loader(*this)
  224. , m_event_handler({}, *this)
  225. , m_container(container)
  226. {
  227. m_cursor_blink_timer = Core::Timer::create_repeating(500, [this] {
  228. if (!is_focused_context())
  229. return;
  230. if (m_cursor_position.node() && m_cursor_position.node()->layout_node()) {
  231. m_cursor_blink_state = !m_cursor_blink_state;
  232. m_cursor_position.node()->layout_node()->set_needs_display();
  233. }
  234. }).release_value_but_fixme_should_propagate_errors();
  235. }
  236. BrowsingContext::~BrowsingContext() = default;
  237. void BrowsingContext::visit_edges(Cell::Visitor& visitor)
  238. {
  239. Base::visit_edges(visitor);
  240. for (auto& entry : m_session_history)
  241. visitor.visit(entry);
  242. visitor.visit(m_container);
  243. visitor.visit(m_window_proxy);
  244. visitor.visit(m_opener_browsing_context);
  245. visitor.visit(m_group);
  246. visitor.visit(m_parent);
  247. visitor.visit(m_first_child);
  248. visitor.visit(m_last_child);
  249. visitor.visit(m_next_sibling);
  250. visitor.visit(m_previous_sibling);
  251. }
  252. // https://html.spec.whatwg.org/multipage/document-sequences.html#bc-traversable
  253. JS::NonnullGCPtr<HTML::TraversableNavigable> BrowsingContext::top_level_traversable() const
  254. {
  255. // A browsing context's top-level traversable is its active document's node navigable's top-level traversable.
  256. auto traversable = active_document()->navigable()->top_level_traversable();
  257. VERIFY(traversable);
  258. VERIFY(traversable->is_top_level_traversable());
  259. return *traversable;
  260. }
  261. void BrowsingContext::did_edit(Badge<EditEventHandler>)
  262. {
  263. reset_cursor_blink_cycle();
  264. if (m_cursor_position.node() && is<DOM::Text>(*m_cursor_position.node())) {
  265. auto& text_node = static_cast<DOM::Text&>(*m_cursor_position.node());
  266. if (auto* text_node_owner = text_node.editable_text_node_owner())
  267. text_node_owner->did_edit_text_node({});
  268. }
  269. }
  270. void BrowsingContext::reset_cursor_blink_cycle()
  271. {
  272. m_cursor_blink_state = true;
  273. m_cursor_blink_timer->restart();
  274. if (m_cursor_position.is_valid() && m_cursor_position.node()->layout_node())
  275. m_cursor_position.node()->layout_node()->set_needs_display();
  276. }
  277. // https://html.spec.whatwg.org/multipage/browsers.html#top-level-browsing-context
  278. bool BrowsingContext::is_top_level() const
  279. {
  280. // 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.
  281. return !parent();
  282. }
  283. bool BrowsingContext::is_focused_context() const
  284. {
  285. return m_page && &m_page->focused_context() == this;
  286. }
  287. void BrowsingContext::scroll_to(CSSPixelPoint position)
  288. {
  289. // NOTE: Scrolling to a position requires up-to-date layout *unless* we're scrolling to (0, 0)
  290. // as (0, 0) is always guaranteed to be a valid scroll position.
  291. if (!position.is_zero()) {
  292. if (active_document())
  293. active_document()->update_layout();
  294. }
  295. if (m_page && this == &m_page->top_level_browsing_context())
  296. m_page->client().page_did_request_scroll_to(position);
  297. }
  298. void BrowsingContext::scroll_to_anchor(DeprecatedString const& fragment)
  299. {
  300. JS::GCPtr<DOM::Document> document = active_document();
  301. if (!document)
  302. return;
  303. auto element = document->get_element_by_id(fragment);
  304. if (!element) {
  305. auto candidates = document->get_elements_by_name(MUST(String::from_deprecated_string(fragment)));
  306. for (auto& candidate : candidates->collect_matching_elements()) {
  307. if (is<HTML::HTMLAnchorElement>(*candidate)) {
  308. element = &verify_cast<HTML::HTMLAnchorElement>(*candidate);
  309. break;
  310. }
  311. }
  312. }
  313. if (!element)
  314. return;
  315. document->update_layout();
  316. if (!element->layout_node())
  317. return;
  318. auto& layout_node = *element->layout_node();
  319. auto const viewport_rect = document->viewport_rect();
  320. CSSPixelRect target_rect { layout_node.box_type_agnostic_position(), { viewport_rect.width(), viewport_rect.height() } };
  321. if (is<Layout::Box>(layout_node)) {
  322. auto& layout_box = verify_cast<Layout::Box>(layout_node);
  323. auto padding_box = layout_box.box_model().padding_box();
  324. target_rect.translate_by(-padding_box.left, -padding_box.top);
  325. }
  326. if (m_page && this == &m_page->top_level_browsing_context())
  327. m_page->client().page_did_request_scroll_into_view(target_rect);
  328. }
  329. JS::GCPtr<BrowsingContext> BrowsingContext::top_level_browsing_context() const
  330. {
  331. auto const* start = this;
  332. // 1. If start's active document is not fully active, then return null.
  333. if (!start->active_document()->is_fully_active()) {
  334. return nullptr;
  335. }
  336. // 2. Let navigable be start's active document's node navigable.
  337. auto navigable = start->active_document()->navigable();
  338. // 3. While navigable's parent is not null, set navigable to navigable's parent.
  339. while (navigable->parent()) {
  340. navigable = navigable->parent();
  341. }
  342. // 4. Return navigable's active browsing context.
  343. return navigable->active_browsing_context();
  344. }
  345. CSSPixelRect BrowsingContext::to_top_level_rect(CSSPixelRect const& a_rect)
  346. {
  347. auto rect = a_rect;
  348. rect.set_location(to_top_level_position(a_rect.location()));
  349. return rect;
  350. }
  351. CSSPixelPoint BrowsingContext::to_top_level_position(CSSPixelPoint a_position)
  352. {
  353. auto position = a_position;
  354. for (auto ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  355. if (ancestor->is_top_level())
  356. break;
  357. if (!ancestor->container())
  358. return {};
  359. if (!ancestor->container()->layout_node())
  360. return {};
  361. position.translate_by(ancestor->container()->layout_node()->box_type_agnostic_position());
  362. }
  363. return position;
  364. }
  365. void BrowsingContext::set_cursor_position(DOM::Position position)
  366. {
  367. if (m_cursor_position == position)
  368. return;
  369. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  370. m_cursor_position.node()->layout_node()->set_needs_display();
  371. m_cursor_position = move(position);
  372. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  373. m_cursor_position.node()->layout_node()->set_needs_display();
  374. reset_cursor_blink_cycle();
  375. }
  376. static DeprecatedString visible_text_in_range(DOM::Range const& range)
  377. {
  378. // NOTE: This is an adaption of Range stringification, but we skip over DOM nodes that don't have a corresponding layout node.
  379. StringBuilder builder;
  380. if (range.start_container() == range.end_container() && is<DOM::Text>(*range.start_container())) {
  381. if (!range.start_container()->layout_node())
  382. return ""sv;
  383. return static_cast<DOM::Text const&>(*range.start_container()).data().substring(range.start_offset(), range.end_offset() - range.start_offset());
  384. }
  385. if (is<DOM::Text>(*range.start_container()) && range.start_container()->layout_node())
  386. builder.append(static_cast<DOM::Text const&>(*range.start_container()).data().substring_view(range.start_offset()));
  387. for (DOM::Node const* node = range.start_container(); node != range.end_container()->next_sibling(); node = node->next_in_pre_order()) {
  388. if (is<DOM::Text>(*node) && range.contains_node(*node) && node->layout_node())
  389. builder.append(static_cast<DOM::Text const&>(*node).data());
  390. }
  391. if (is<DOM::Text>(*range.end_container()) && range.end_container()->layout_node())
  392. builder.append(static_cast<DOM::Text const&>(*range.end_container()).data().substring_view(0, range.end_offset()));
  393. return builder.to_deprecated_string();
  394. }
  395. DeprecatedString BrowsingContext::selected_text() const
  396. {
  397. auto* document = active_document();
  398. if (!document)
  399. return ""sv;
  400. auto selection = const_cast<DOM::Document&>(*document).get_selection();
  401. auto range = selection->range();
  402. if (!range)
  403. return ""sv;
  404. return visible_text_in_range(*range);
  405. }
  406. void BrowsingContext::select_all()
  407. {
  408. auto* document = active_document();
  409. if (!document)
  410. return;
  411. auto* body = document->body();
  412. if (!body)
  413. return;
  414. auto selection = document->get_selection();
  415. if (!selection)
  416. return;
  417. (void)selection->select_all_children(*document->body());
  418. }
  419. void BrowsingContext::register_frame_nesting(AK::URL const& url)
  420. {
  421. m_frame_nesting_levels.ensure(url)++;
  422. }
  423. bool BrowsingContext::is_frame_nesting_allowed(AK::URL const& url) const
  424. {
  425. return m_frame_nesting_levels.get(url).value_or(0) < 3;
  426. }
  427. bool BrowsingContext::increment_cursor_position_offset()
  428. {
  429. if (!m_cursor_position.increment_offset())
  430. return false;
  431. reset_cursor_blink_cycle();
  432. return true;
  433. }
  434. bool BrowsingContext::decrement_cursor_position_offset()
  435. {
  436. if (!m_cursor_position.decrement_offset())
  437. return false;
  438. reset_cursor_blink_cycle();
  439. return true;
  440. }
  441. DOM::Document* BrowsingContext::container_document()
  442. {
  443. if (auto* container = this->container())
  444. return &container->document();
  445. return nullptr;
  446. }
  447. DOM::Document const* BrowsingContext::container_document() const
  448. {
  449. if (auto* container = this->container())
  450. return &container->document();
  451. return nullptr;
  452. }
  453. // https://html.spec.whatwg.org/#rendering-opportunity
  454. bool BrowsingContext::has_a_rendering_opportunity() const
  455. {
  456. // 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,
  457. // accounting for hardware refresh rate constraints and user agent throttling for performance reasons, but considering content presentable even if it's outside the viewport.
  458. // FIXME: We should at the very least say `false` here if we're an inactive browser tab.
  459. return true;
  460. }
  461. // https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-browsing-context
  462. JS::GCPtr<DOM::Node> BrowsingContext::currently_focused_area()
  463. {
  464. // 1. If topLevelBC does not have system focus, then return null.
  465. if (!is_focused_context())
  466. return nullptr;
  467. // 2. Let candidate be topLevelBC's active document.
  468. auto* candidate = active_document();
  469. // 3. While candidate's focused area is a browsing context container with a non-null nested browsing context:
  470. // set candidate to the active document of that browsing context container's nested browsing context.
  471. while (candidate->focused_element()
  472. && is<HTML::NavigableContainer>(candidate->focused_element())
  473. && static_cast<HTML::NavigableContainer&>(*candidate->focused_element()).nested_browsing_context()) {
  474. candidate = static_cast<HTML::NavigableContainer&>(*candidate->focused_element()).nested_browsing_context()->active_document();
  475. }
  476. // 4. If candidate's focused area is non-null, set candidate to candidate's focused area.
  477. if (candidate->focused_element()) {
  478. // NOTE: We return right away here instead of assigning to candidate,
  479. // since that would require compromising type safety.
  480. return candidate->focused_element();
  481. }
  482. // 5. Return candidate.
  483. return candidate;
  484. }
  485. // https://html.spec.whatwg.org/#the-rules-for-choosing-a-browsing-context-given-a-browsing-context-name
  486. BrowsingContext::ChosenBrowsingContext BrowsingContext::choose_a_browsing_context(StringView name, TokenizedFeature::NoOpener no_opener, ActivateTab activate_tab)
  487. {
  488. // The rules for choosing a browsing context, given a browsing context name name, a browsing context current, and
  489. // a boolean noopener are as follows:
  490. JS::GCPtr<AbstractBrowsingContext> matching_name_in_tree = nullptr;
  491. top_level_browsing_context()->for_each_in_subtree([&](auto& context) {
  492. if (context.name() == name) {
  493. matching_name_in_tree = &context;
  494. return IterationDecision::Break;
  495. }
  496. return IterationDecision::Continue;
  497. });
  498. // 1. Let chosen be null.
  499. JS::GCPtr<AbstractBrowsingContext> chosen = nullptr;
  500. // 2. Let windowType be "existing or none".
  501. auto window_type = WindowType::ExistingOrNone;
  502. // 3. Let sandboxingFlagSet be current's active document's active sandboxing flag set.
  503. auto sandboxing_flag_set = active_document()->active_sandboxing_flag_set();
  504. // 4. If name is the empty string or an ASCII case-insensitive match for "_self", then set chosen to current.
  505. if (name.is_empty() || Infra::is_ascii_case_insensitive_match(name, "_self"sv)) {
  506. chosen = this;
  507. }
  508. // 5. Otherwise, if name is an ASCII case-insensitive match for "_parent", set chosen to current's parent browsing
  509. // context, if any, and current otherwise.
  510. else if (Infra::is_ascii_case_insensitive_match(name, "_parent"sv)) {
  511. if (auto parent = this->parent())
  512. chosen = parent;
  513. else
  514. chosen = this;
  515. }
  516. // 6. Otherwise, if name is an ASCII case-insensitive match for "_top", set chosen to current's top-level browsing
  517. // context, if any, and current otherwise.
  518. else if (Infra::is_ascii_case_insensitive_match(name, "_top"sv)) {
  519. chosen = top_level_browsing_context();
  520. }
  521. // 7. Otherwise, if name is not an ASCII case-insensitive match for "_blank", there exists a browsing context
  522. // whose name is the same as name, current is familiar with that browsing context, and the user agent
  523. // determines that the two browsing contexts are related enough that it is ok if they reach each other,
  524. // set chosen to that browsing context. If there are multiple matching browsing contexts, the user agent
  525. // should set chosen to one in some arbitrary consistent manner, such as the most recently opened, most
  526. // recently focused, or more closely related.
  527. else if (!Infra::is_ascii_case_insensitive_match(name, "_blank"sv) && matching_name_in_tree) {
  528. chosen = matching_name_in_tree;
  529. } else {
  530. // 8. Otherwise, a new browsing context is being requested, and what happens depends on the user agent's
  531. // configuration and abilities — it is determined by the rules given for the first applicable option from
  532. // the following list:
  533. // --> If current's active window does not have transient activation and the user agent has been configured to
  534. // not show popups (i.e., the user agent has a "popup blocker" enabled)
  535. VERIFY(m_page);
  536. if (!active_window()->has_transient_activation() && m_page->should_block_pop_ups()) {
  537. // FIXME: The user agent may inform the user that a popup has been blocked.
  538. dbgln("Pop-up blocked!");
  539. }
  540. // --> If sandboxingFlagSet has the sandboxed auxiliary navigation browsing context flag set
  541. else if (has_flag(sandboxing_flag_set, SandboxingFlagSet::SandboxedAuxiliaryNavigation)) {
  542. // FIXME: The user agent may report to a developer console that a popup has been blocked.
  543. dbgln("Pop-up blocked!");
  544. }
  545. // --> If the user agent has been configured such that in this instance it will create a new browsing context
  546. else if (true) { // FIXME: When is this the case?
  547. // 1. Set windowType to "new and unrestricted".
  548. window_type = WindowType::NewAndUnrestricted;
  549. // 2. If current's top-level browsing context's active document's cross-origin opener policy's value is
  550. // "same-origin" or "same-origin-plus-COEP", then:
  551. 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) {
  552. // 1. Let currentDocument be current's active document.
  553. auto* current_document = top_level_browsing_context()->active_document();
  554. // 2. If currentDocument's origin is not same origin with currentDocument's relevant settings object's
  555. // top-level origin, then set noopener to true, name to "_blank", and windowType to "new with no opener".
  556. if (!current_document->origin().is_same_origin(current_document->relevant_settings_object().top_level_origin)) {
  557. no_opener = TokenizedFeature::NoOpener::Yes;
  558. name = "_blank"sv;
  559. window_type = WindowType::NewWithNoOpener;
  560. }
  561. }
  562. // 3. If noopener is true, then set chosen to the result of creating a new top-level browsing context.
  563. if (no_opener == TokenizedFeature::NoOpener::Yes) {
  564. auto handle = m_page->client().page_did_request_new_tab(activate_tab);
  565. chosen = RemoteBrowsingContext::create_a_new_remote_browsing_context(handle);
  566. }
  567. // 4. Otherwise:
  568. else {
  569. // 1. Set chosen to the result of creating a new auxiliary browsing context with current.
  570. // FIXME: We have no concept of auxiliary browsing context
  571. chosen = HTML::create_a_new_top_level_browsing_context_and_document(*m_page).release_value_but_fixme_should_propagate_errors().browsing_context;
  572. // 2. If sandboxingFlagSet's sandboxed navigation browsing context flag is set, then current must be
  573. // set as chosen's one permitted sandboxed navigator.
  574. // FIXME: We have no concept of one permitted sandboxed navigator
  575. }
  576. // 5. If sandboxingFlagSet's sandbox propagates to auxiliary browsing contexts flag is set, then all the
  577. // flags that are set in sandboxingFlagSet must be set in chosen's popup sandboxing flag set.
  578. // FIXME: Our BrowsingContexts do not have SandboxingFlagSets yet, only documents do
  579. // 6. If name is not an ASCII case-insensitive match for "_blank", then set chosen's name to name.
  580. if (!Infra::is_ascii_case_insensitive_match(name, "_blank"sv))
  581. chosen->set_name(String::from_utf8(name).release_value_but_fixme_should_propagate_errors());
  582. }
  583. // --> If the user agent has been configured such that in this instance t will reuse current
  584. else if (false) { // FIXME: When is this the case?
  585. // Set chosen to current.
  586. chosen = *this;
  587. }
  588. // --> If the user agent has been configured such that in this instance it will not find a browsing context
  589. else if (false) { // FIXME: When is this the case?
  590. // Do nothing.
  591. }
  592. }
  593. // 9. Return chosen and windowType.
  594. return { chosen.ptr(), window_type };
  595. }
  596. // https://html.spec.whatwg.org/multipage/dom.html#still-on-its-initial-about:blank-document
  597. bool BrowsingContext::still_on_its_initial_about_blank_document() const
  598. {
  599. // A browsing context browsingContext is still on its initial about:blank Document
  600. // if browsingContext's session history's size is 1
  601. // and browsingContext's session history[0]'s document's is initial about:blank is true.
  602. return m_session_history.size() == 1
  603. && m_session_history[0]->document_state->document()
  604. && m_session_history[0]->document_state->document()->is_initial_about_blank();
  605. }
  606. DOM::Document const* BrowsingContext::active_document() const
  607. {
  608. auto* window = active_window();
  609. if (!window)
  610. return nullptr;
  611. return &window->associated_document();
  612. }
  613. DOM::Document* BrowsingContext::active_document()
  614. {
  615. auto* window = active_window();
  616. if (!window)
  617. return nullptr;
  618. return &window->associated_document();
  619. }
  620. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  621. HTML::Window* BrowsingContext::active_window()
  622. {
  623. return m_window_proxy->window();
  624. }
  625. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  626. HTML::Window const* BrowsingContext::active_window() const
  627. {
  628. return m_window_proxy->window();
  629. }
  630. HTML::WindowProxy* BrowsingContext::window_proxy()
  631. {
  632. return m_window_proxy.ptr();
  633. }
  634. HTML::WindowProxy const* BrowsingContext::window_proxy() const
  635. {
  636. return m_window_proxy.ptr();
  637. }
  638. void BrowsingContext::set_window_proxy(JS::GCPtr<WindowProxy> window_proxy)
  639. {
  640. m_window_proxy = move(window_proxy);
  641. }
  642. void BrowsingContext::scroll_offset_did_change()
  643. {
  644. // https://w3c.github.io/csswg-drafts/cssom-view-1/#scrolling-events
  645. // Whenever a viewport gets scrolled (whether in response to user interaction or by an API), the user agent must run these steps:
  646. // 1. Let doc be the viewport’s associated Document.
  647. auto* doc = active_document();
  648. VERIFY(doc);
  649. // 2. If doc is already in doc’s pending scroll event targets, abort these steps.
  650. for (auto& target : doc->pending_scroll_event_targets()) {
  651. if (target.ptr() == doc)
  652. return;
  653. }
  654. // 3. Append doc to doc’s pending scroll event targets.
  655. doc->pending_scroll_event_targets().append(*doc);
  656. }
  657. BrowsingContextGroup* BrowsingContext::group()
  658. {
  659. return m_group;
  660. }
  661. void BrowsingContext::set_group(BrowsingContextGroup* group)
  662. {
  663. m_group = group;
  664. }
  665. // https://html.spec.whatwg.org/multipage/browsers.html#bcg-remove
  666. void BrowsingContext::remove()
  667. {
  668. // 1. Assert: browsingContext's group is non-null, because a browsing context only gets discarded once.
  669. VERIFY(group());
  670. // 2. Let group be browsingContext's group.
  671. JS::NonnullGCPtr<BrowsingContextGroup> group = *this->group();
  672. // 3. Set browsingContext's group to null.
  673. set_group(nullptr);
  674. // 4. Remove browsingContext from group's browsing context set.
  675. group->browsing_context_set().remove(*this);
  676. // 5. If group's browsing context set is empty, then remove group from the user agent's browsing context group set.
  677. // NOTE: This is done by ~BrowsingContextGroup() when the refcount reaches 0.
  678. }
  679. // https://html.spec.whatwg.org/multipage/origin.html#one-permitted-sandboxed-navigator
  680. BrowsingContext const* BrowsingContext::the_one_permitted_sandboxed_navigator() const
  681. {
  682. // FIXME: Implement this.
  683. return nullptr;
  684. }
  685. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  686. Vector<JS::Handle<DOM::Document>> BrowsingContext::document_family() const
  687. {
  688. HashTable<DOM::Document*> documents;
  689. for (auto& entry : m_session_history) {
  690. if (!entry->document_state->document())
  691. continue;
  692. if (documents.set(const_cast<DOM::Document*>(entry->document_state->document().ptr())) == AK::HashSetResult::ReplacedExistingEntry)
  693. continue;
  694. for (auto& context : entry->document_state->document()->list_of_descendant_browsing_contexts()) {
  695. for (auto& document : context->document_family()) {
  696. documents.set(document.ptr());
  697. }
  698. }
  699. }
  700. Vector<JS::Handle<DOM::Document>> family;
  701. for (auto* document : documents) {
  702. family.append(*document);
  703. }
  704. return family;
  705. }
  706. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  707. bool BrowsingContext::document_family_contains(DOM::Document const& document) const
  708. {
  709. return document_family().first_matching([&](auto& entry) { return entry.ptr() == &document; }).has_value();
  710. }
  711. VisibilityState BrowsingContext::system_visibility_state() const
  712. {
  713. return m_system_visibility_state;
  714. }
  715. // https://html.spec.whatwg.org/multipage/interaction.html#system-visibility-state
  716. void BrowsingContext::set_system_visibility_state(VisibilityState visibility_state)
  717. {
  718. if (m_system_visibility_state == visibility_state)
  719. return;
  720. m_system_visibility_state = visibility_state;
  721. // When a user-agent determines that the system visibility state for top-level browsing context context
  722. // has changed to newState, it must queue a task on the user interaction task source to update
  723. // the visibility state of all the Document objects in the top-level browsing context's document family with newState.
  724. auto document_family = top_level_browsing_context()->document_family();
  725. // From the new navigable version, where it tells us what global object to use here:
  726. // 1. Let document be navigable's active document.
  727. // 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.
  728. // FIXME: Update this function to fully match the navigable version.
  729. VERIFY(active_document());
  730. queue_global_task(Task::Source::UserInteraction, relevant_global_object(*active_document()), [visibility_state, document_family = move(document_family)] {
  731. for (auto& document : document_family) {
  732. document->update_the_visibility_state(visibility_state);
  733. }
  734. });
  735. }
  736. // https://html.spec.whatwg.org/multipage/window-object.html#a-browsing-context-is-discarded
  737. void BrowsingContext::discard()
  738. {
  739. m_has_been_discarded = true;
  740. // 1. Discard all Document objects for all the entries in browsingContext's session history.
  741. for (auto& entry : m_session_history) {
  742. if (entry->document_state->document())
  743. entry->document_state->document()->discard();
  744. }
  745. // AD-HOC:
  746. // FIXME: This should be in the session history!
  747. if (auto* document = active_document())
  748. document->discard();
  749. // 2. If browsingContext is a top-level browsing context, then remove browsingContext.
  750. if (is_top_level())
  751. remove();
  752. // AD-HOC:
  753. if (parent())
  754. parent()->remove_child(*this);
  755. }
  756. // https://html.spec.whatwg.org/multipage/window-object.html#close-a-browsing-context
  757. void BrowsingContext::close()
  758. {
  759. VERIFY(active_document());
  760. // FIXME: 1. If the result of calling prompt to unload with browsingContext's active document is "refuse", then return.
  761. // 2. Unload browsingContext's active document.
  762. active_document()->unload();
  763. // 3. Remove browsingContext from the user interface (e.g., close or hide its tab in a tabbed browser).
  764. if (m_page)
  765. m_page->client().page_did_close_browsing_context(*this);
  766. // 4. Discard browsingContext.
  767. discard();
  768. }
  769. void BrowsingContext::append_child(JS::NonnullGCPtr<BrowsingContext> child)
  770. {
  771. VERIFY(!child->m_parent);
  772. if (m_last_child)
  773. m_last_child->m_next_sibling = child;
  774. child->m_previous_sibling = m_last_child;
  775. child->m_parent = this;
  776. m_last_child = child;
  777. if (!m_first_child)
  778. m_first_child = m_last_child;
  779. }
  780. void BrowsingContext::remove_child(JS::NonnullGCPtr<BrowsingContext> child)
  781. {
  782. VERIFY(child->m_parent.ptr() == this);
  783. if (m_first_child == child)
  784. m_first_child = child->m_next_sibling;
  785. if (m_last_child == child)
  786. m_last_child = child->m_previous_sibling;
  787. if (child->m_next_sibling)
  788. child->m_next_sibling->m_previous_sibling = child->m_previous_sibling;
  789. if (child->m_previous_sibling)
  790. child->m_previous_sibling->m_next_sibling = child->m_next_sibling;
  791. child->m_next_sibling = nullptr;
  792. child->m_previous_sibling = nullptr;
  793. child->m_parent = nullptr;
  794. }
  795. JS::GCPtr<BrowsingContext> BrowsingContext::first_child() const
  796. {
  797. return m_first_child;
  798. }
  799. JS::GCPtr<BrowsingContext> BrowsingContext::next_sibling() const
  800. {
  801. return m_next_sibling;
  802. }
  803. bool BrowsingContext::is_ancestor_of(BrowsingContext const& other) const
  804. {
  805. for (auto ancestor = other.parent(); ancestor; ancestor = ancestor->parent()) {
  806. if (ancestor == this)
  807. return true;
  808. }
  809. return false;
  810. }
  811. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#snapshotting-target-snapshot-params
  812. SandboxingFlagSet determine_the_creation_sandboxing_flags(BrowsingContext const&, JS::GCPtr<DOM::Element>)
  813. {
  814. // FIXME: Populate this once we have the proper flag sets on BrowsingContext
  815. return {};
  816. }
  817. }