BrowsingContext.cpp 34 KB

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