BrowsingContext.cpp 33 KB

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