BrowsingContext.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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/browsers.html#child-browsing-context
  597. bool BrowsingContext::is_child_of(BrowsingContext const& parent) const
  598. {
  599. // A browsing context child is said to be a child browsing context of another browsing context parent,
  600. // if child's container document is non-null and child's container document's browsing context is parent.
  601. return container_document() && container_document()->browsing_context() == &parent;
  602. }
  603. // https://html.spec.whatwg.org/multipage/dom.html#still-on-its-initial-about:blank-document
  604. bool BrowsingContext::still_on_its_initial_about_blank_document() const
  605. {
  606. // A browsing context browsingContext is still on its initial about:blank Document
  607. // if browsingContext's session history's size is 1
  608. // and browsingContext's session history[0]'s document's is initial about:blank is true.
  609. return m_session_history.size() == 1
  610. && m_session_history[0]->document_state->document()
  611. && m_session_history[0]->document_state->document()->is_initial_about_blank();
  612. }
  613. DOM::Document const* BrowsingContext::active_document() const
  614. {
  615. auto* window = active_window();
  616. if (!window)
  617. return nullptr;
  618. return &window->associated_document();
  619. }
  620. DOM::Document* BrowsingContext::active_document()
  621. {
  622. auto* window = active_window();
  623. if (!window)
  624. return nullptr;
  625. return &window->associated_document();
  626. }
  627. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  628. HTML::Window* BrowsingContext::active_window()
  629. {
  630. return m_window_proxy->window();
  631. }
  632. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  633. HTML::Window const* BrowsingContext::active_window() const
  634. {
  635. return m_window_proxy->window();
  636. }
  637. HTML::WindowProxy* BrowsingContext::window_proxy()
  638. {
  639. return m_window_proxy.ptr();
  640. }
  641. HTML::WindowProxy const* BrowsingContext::window_proxy() const
  642. {
  643. return m_window_proxy.ptr();
  644. }
  645. void BrowsingContext::set_window_proxy(JS::GCPtr<WindowProxy> window_proxy)
  646. {
  647. m_window_proxy = move(window_proxy);
  648. }
  649. void BrowsingContext::scroll_offset_did_change()
  650. {
  651. // https://w3c.github.io/csswg-drafts/cssom-view-1/#scrolling-events
  652. // Whenever a viewport gets scrolled (whether in response to user interaction or by an API), the user agent must run these steps:
  653. // 1. Let doc be the viewport’s associated Document.
  654. auto* doc = active_document();
  655. VERIFY(doc);
  656. // 2. If doc is already in doc’s pending scroll event targets, abort these steps.
  657. for (auto& target : doc->pending_scroll_event_targets()) {
  658. if (target.ptr() == doc)
  659. return;
  660. }
  661. // 3. Append doc to doc’s pending scroll event targets.
  662. doc->pending_scroll_event_targets().append(*doc);
  663. }
  664. BrowsingContextGroup* BrowsingContext::group()
  665. {
  666. return m_group;
  667. }
  668. void BrowsingContext::set_group(BrowsingContextGroup* group)
  669. {
  670. m_group = group;
  671. }
  672. // https://html.spec.whatwg.org/multipage/browsers.html#bcg-remove
  673. void BrowsingContext::remove()
  674. {
  675. // 1. Assert: browsingContext's group is non-null, because a browsing context only gets discarded once.
  676. VERIFY(group());
  677. // 2. Let group be browsingContext's group.
  678. JS::NonnullGCPtr<BrowsingContextGroup> group = *this->group();
  679. // 3. Set browsingContext's group to null.
  680. set_group(nullptr);
  681. // 4. Remove browsingContext from group's browsing context set.
  682. group->browsing_context_set().remove(*this);
  683. // 5. If group's browsing context set is empty, then remove group from the user agent's browsing context group set.
  684. // NOTE: This is done by ~BrowsingContextGroup() when the refcount reaches 0.
  685. }
  686. // https://html.spec.whatwg.org/multipage/origin.html#one-permitted-sandboxed-navigator
  687. BrowsingContext const* BrowsingContext::the_one_permitted_sandboxed_navigator() const
  688. {
  689. // FIXME: Implement this.
  690. return nullptr;
  691. }
  692. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  693. Vector<JS::Handle<DOM::Document>> BrowsingContext::document_family() const
  694. {
  695. HashTable<DOM::Document*> documents;
  696. for (auto& entry : m_session_history) {
  697. if (!entry->document_state->document())
  698. continue;
  699. if (documents.set(const_cast<DOM::Document*>(entry->document_state->document().ptr())) == AK::HashSetResult::ReplacedExistingEntry)
  700. continue;
  701. for (auto& context : entry->document_state->document()->list_of_descendant_browsing_contexts()) {
  702. for (auto& document : context->document_family()) {
  703. documents.set(document.ptr());
  704. }
  705. }
  706. }
  707. Vector<JS::Handle<DOM::Document>> family;
  708. for (auto* document : documents) {
  709. family.append(*document);
  710. }
  711. return family;
  712. }
  713. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  714. bool BrowsingContext::document_family_contains(DOM::Document const& document) const
  715. {
  716. return document_family().first_matching([&](auto& entry) { return entry.ptr() == &document; }).has_value();
  717. }
  718. VisibilityState BrowsingContext::system_visibility_state() const
  719. {
  720. return m_system_visibility_state;
  721. }
  722. // https://html.spec.whatwg.org/multipage/interaction.html#system-visibility-state
  723. void BrowsingContext::set_system_visibility_state(VisibilityState visibility_state)
  724. {
  725. if (m_system_visibility_state == visibility_state)
  726. return;
  727. m_system_visibility_state = visibility_state;
  728. // When a user-agent determines that the system visibility state for top-level browsing context context
  729. // has changed to newState, it must queue a task on the user interaction task source to update
  730. // the visibility state of all the Document objects in the top-level browsing context's document family with newState.
  731. auto document_family = top_level_browsing_context()->document_family();
  732. // From the new navigable version, where it tells us what global object to use here:
  733. // 1. Let document be navigable's active document.
  734. // 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.
  735. // FIXME: Update this function to fully match the navigable version.
  736. VERIFY(active_document());
  737. queue_global_task(Task::Source::UserInteraction, relevant_global_object(*active_document()), [visibility_state, document_family = move(document_family)] {
  738. for (auto& document : document_family) {
  739. document->update_the_visibility_state(visibility_state);
  740. }
  741. });
  742. }
  743. // https://html.spec.whatwg.org/multipage/window-object.html#a-browsing-context-is-discarded
  744. void BrowsingContext::discard()
  745. {
  746. m_has_been_discarded = true;
  747. // 1. Discard all Document objects for all the entries in browsingContext's session history.
  748. for (auto& entry : m_session_history) {
  749. if (entry->document_state->document())
  750. entry->document_state->document()->discard();
  751. }
  752. // AD-HOC:
  753. // FIXME: This should be in the session history!
  754. if (auto* document = active_document())
  755. document->discard();
  756. // 2. If browsingContext is a top-level browsing context, then remove browsingContext.
  757. if (is_top_level())
  758. remove();
  759. // AD-HOC:
  760. if (parent())
  761. parent()->remove_child(*this);
  762. }
  763. // https://html.spec.whatwg.org/multipage/window-object.html#close-a-browsing-context
  764. void BrowsingContext::close()
  765. {
  766. VERIFY(active_document());
  767. // FIXME: 1. If the result of calling prompt to unload with browsingContext's active document is "refuse", then return.
  768. // 2. Unload browsingContext's active document.
  769. active_document()->unload();
  770. // 3. Remove browsingContext from the user interface (e.g., close or hide its tab in a tabbed browser).
  771. if (m_page)
  772. m_page->client().page_did_close_browsing_context(*this);
  773. // 4. Discard browsingContext.
  774. discard();
  775. }
  776. void BrowsingContext::append_child(JS::NonnullGCPtr<BrowsingContext> child)
  777. {
  778. VERIFY(!child->m_parent);
  779. if (m_last_child)
  780. m_last_child->m_next_sibling = child;
  781. child->m_previous_sibling = m_last_child;
  782. child->m_parent = this;
  783. m_last_child = child;
  784. if (!m_first_child)
  785. m_first_child = m_last_child;
  786. }
  787. void BrowsingContext::remove_child(JS::NonnullGCPtr<BrowsingContext> child)
  788. {
  789. VERIFY(child->m_parent.ptr() == this);
  790. if (m_first_child == child)
  791. m_first_child = child->m_next_sibling;
  792. if (m_last_child == child)
  793. m_last_child = child->m_previous_sibling;
  794. if (child->m_next_sibling)
  795. child->m_next_sibling->m_previous_sibling = child->m_previous_sibling;
  796. if (child->m_previous_sibling)
  797. child->m_previous_sibling->m_next_sibling = child->m_next_sibling;
  798. child->m_next_sibling = nullptr;
  799. child->m_previous_sibling = nullptr;
  800. child->m_parent = nullptr;
  801. }
  802. JS::GCPtr<BrowsingContext> BrowsingContext::first_child() const
  803. {
  804. return m_first_child;
  805. }
  806. JS::GCPtr<BrowsingContext> BrowsingContext::next_sibling() const
  807. {
  808. return m_next_sibling;
  809. }
  810. bool BrowsingContext::is_ancestor_of(BrowsingContext const& other) const
  811. {
  812. for (auto ancestor = other.parent(); ancestor; ancestor = ancestor->parent()) {
  813. if (ancestor == this)
  814. return true;
  815. }
  816. return false;
  817. }
  818. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#snapshotting-target-snapshot-params
  819. SandboxingFlagSet determine_the_creation_sandboxing_flags(BrowsingContext const&, JS::GCPtr<DOM::Element>)
  820. {
  821. // FIXME: Populate this once we have the proper flag sets on BrowsingContext
  822. return {};
  823. }
  824. }