BrowsingContext.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  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/Event.h>
  9. #include <LibWeb/DOM/HTMLCollection.h>
  10. #include <LibWeb/DOM/Range.h>
  11. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  12. #include <LibWeb/HTML/BrowsingContext.h>
  13. #include <LibWeb/HTML/BrowsingContextContainer.h>
  14. #include <LibWeb/HTML/BrowsingContextGroup.h>
  15. #include <LibWeb/HTML/CrossOrigin/CrossOriginOpenerPolicy.h>
  16. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  17. #include <LibWeb/HTML/HTMLAnchorElement.h>
  18. #include <LibWeb/HTML/HTMLInputElement.h>
  19. #include <LibWeb/HTML/SandboxingFlagSet.h>
  20. #include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
  21. #include <LibWeb/HTML/Window.h>
  22. #include <LibWeb/HTML/WindowProxy.h>
  23. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  24. #include <LibWeb/Layout/BreakNode.h>
  25. #include <LibWeb/Layout/InitialContainingBlock.h>
  26. #include <LibWeb/Layout/TextNode.h>
  27. #include <LibWeb/Page/Page.h>
  28. #include <LibWeb/URL/URL.h>
  29. namespace Web::HTML {
  30. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#matches-about:blank
  31. static bool url_matches_about_blank(AK::URL const& url)
  32. {
  33. // 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.
  34. return url.scheme() == "about"sv
  35. && url.path() == "blank"sv
  36. && url.username().is_empty()
  37. && url.password().is_empty()
  38. && url.host().is_null();
  39. }
  40. // https://html.spec.whatwg.org/multipage/browsers.html#determining-the-origin
  41. HTML::Origin determine_the_origin(BrowsingContext const& browsing_context, Optional<AK::URL> url, SandboxingFlagSet sandbox_flags, Optional<HTML::Origin> invocation_origin)
  42. {
  43. // 1. If sandboxFlags has its sandboxed origin browsing context flag set, then return a new opaque origin.
  44. if (sandbox_flags.flags & SandboxingFlagSet::SandboxedOrigin) {
  45. return HTML::Origin {};
  46. }
  47. // 2. If url is null, then return a new opaque origin.
  48. if (!url.has_value()) {
  49. return HTML::Origin {};
  50. }
  51. // 3. If invocationOrigin is non-null and url matches about:blank, then return invocationOrigin.
  52. if (invocation_origin.has_value() && url_matches_about_blank(*url)) {
  53. return invocation_origin.value();
  54. }
  55. // 4. If url is about:srcdoc, then return the origin of browsingContext's container document.
  56. if (url == AK::URL("about:srcdoc")) {
  57. VERIFY(browsing_context.container_document());
  58. return browsing_context.container_document()->origin();
  59. }
  60. // 5. Return url's origin.
  61. return URL::url_origin(*url);
  62. }
  63. // https://html.spec.whatwg.org/multipage/browsers.html#creating-a-new-top-level-browsing-context
  64. JS::NonnullGCPtr<BrowsingContext> BrowsingContext::create_a_new_top_level_browsing_context(Web::Page& page)
  65. {
  66. // 1. Let group be the result of creating a new browsing context group.
  67. auto group = BrowsingContextGroup::create_a_new_browsing_context_group(page);
  68. // 2. Return group's browsing context set[0].
  69. return *(*group->browsing_context_set().begin());
  70. }
  71. // https://html.spec.whatwg.org/multipage/browsers.html#creating-a-new-browsing-context
  72. JS::NonnullGCPtr<BrowsingContext> BrowsingContext::create_a_new_browsing_context(Page& page, JS::GCPtr<DOM::Document> creator, JS::GCPtr<DOM::Element> embedder, BrowsingContextGroup&)
  73. {
  74. // 1. Let browsingContext be a new browsing context.
  75. BrowsingContextContainer* container = (embedder && is<BrowsingContextContainer>(*embedder)) ? static_cast<BrowsingContextContainer*>(embedder.ptr()) : nullptr;
  76. auto browsing_context = Bindings::main_thread_vm().heap().allocate_without_realm<BrowsingContext>(page, container);
  77. // 2. Let unsafeContextCreationTime be the unsafe shared current time.
  78. [[maybe_unused]] auto unsafe_context_creation_time = HighResolutionTime::unsafe_shared_current_time();
  79. // 3. If creator is non-null, then set browsingContext's creator origin to return creator's origin,
  80. // browsingContext's creator URL to return creator's URL,
  81. // browsingContext's creator base URL to return creator's base URL,
  82. // FIXME: and browsingContext's virtual browsing context group ID to creator's top-level browsing context's virtual browsing context group ID.
  83. if (creator) {
  84. browsing_context->m_creator_origin = creator->origin();
  85. browsing_context->m_creator_url = creator->url();
  86. browsing_context->m_creator_base_url = creator->base_url();
  87. }
  88. // FIXME: 4. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and embedded.
  89. SandboxingFlagSet sandbox_flags;
  90. // 5. Let origin be the result of determining the origin given browsingContext, about:blank, sandboxFlags, and browsingContext's creator origin.
  91. auto origin = determine_the_origin(*browsing_context, AK::URL("about:blank"), sandbox_flags, browsing_context->m_creator_origin);
  92. // FIXME: 6. Let permissionsPolicy be the result of creating a permissions policy given browsingContext and origin. [PERMISSIONSPOLICY]
  93. // FIXME: 7. Let agent be the result of obtaining a similar-origin window agent given origin, group, and false.
  94. JS::GCPtr<Window> window;
  95. // 8. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
  96. auto realm_execution_context = Bindings::create_a_new_javascript_realm(
  97. Bindings::main_thread_vm(),
  98. [&](JS::Realm& realm) -> JS::Object* {
  99. browsing_context->m_window_proxy = realm.heap().allocate<WindowProxy>(realm, realm).release_allocated_value_but_fixme_should_propagate_errors();
  100. // - For the global object, create a new Window object.
  101. window = HTML::Window::create(realm);
  102. return window.ptr();
  103. },
  104. [&](JS::Realm&) -> JS::Object* {
  105. // - For the global this binding, use browsingContext's WindowProxy object.
  106. return browsing_context->m_window_proxy;
  107. });
  108. // 9. Let topLevelCreationURL be about:blank if embedder is null; otherwise embedder's relevant settings object's top-level creation URL.
  109. auto top_level_creation_url = !embedder ? AK::URL("about:blank") : relevant_settings_object(*embedder).top_level_creation_url;
  110. // 10. Let topLevelOrigin be origin if embedder is null; otherwise embedder's relevant settings object's top-level origin.
  111. auto top_level_origin = !embedder ? origin : relevant_settings_object(*embedder).origin();
  112. // 11. Set up a window environment settings object with about:blank, realm execution context, null, topLevelCreationURL, and topLevelOrigin.
  113. HTML::WindowEnvironmentSettingsObject::setup(
  114. AK::URL("about:blank"),
  115. move(realm_execution_context),
  116. {},
  117. top_level_creation_url,
  118. top_level_origin);
  119. // 12. Let loadTimingInfo be a new document load timing info with its navigation start time set to the result of calling
  120. // coarsen time with unsafeContextCreationTime and the new environment settings object's cross-origin isolated capability.
  121. auto load_timing_info = DOM::DocumentLoadTimingInfo();
  122. load_timing_info.navigation_start_time = HighResolutionTime::coarsen_time(
  123. unsafe_context_creation_time,
  124. verify_cast<WindowEnvironmentSettingsObject>(Bindings::host_defined_environment_settings_object(window->realm())).cross_origin_isolated_capability() == CanUseCrossOriginIsolatedAPIs::Yes);
  125. // 13. Let coop be a new cross-origin opener policy.
  126. auto coop = CrossOriginOpenerPolicy {};
  127. // 14. If creator is non-null and creator's origin is same origin with creator's relevant settings object's top-level origin,
  128. // then set coop to creator's browsing context's top-level browsing context's active document's cross-origin opener policy.
  129. if (creator && creator->origin().is_same_origin(relevant_settings_object(*creator).top_level_origin)) {
  130. VERIFY(creator->browsing_context());
  131. auto* top_level_document = creator->browsing_context()->top_level_browsing_context().active_document();
  132. VERIFY(top_level_document);
  133. coop = top_level_document->cross_origin_opener_policy();
  134. }
  135. // 15. Let document be a new Document, marked as an HTML document in quirks mode,
  136. // whose content type is "text/html",
  137. // origin is origin,
  138. // FIXME: active sandboxing flag set is sandboxFlags,
  139. // FIXME: permissions policy is permissionsPolicy,
  140. // cross-origin opener policy is coop,
  141. // load timing info is loadTimingInfo,
  142. // FIXME: navigation id is null,
  143. // and which is ready for post-load tasks.
  144. auto document = DOM::Document::create(window->realm()).release_value_but_fixme_should_propagate_errors();
  145. // Non-standard
  146. document->set_window({}, *window);
  147. window->set_associated_document(*document);
  148. document->set_quirks_mode(DOM::QuirksMode::Yes);
  149. document->set_content_type("text/html");
  150. document->set_origin(origin);
  151. document->set_url(AK::URL("about:blank"));
  152. document->set_cross_origin_opener_policy(coop);
  153. document->set_load_timing_info(load_timing_info);
  154. document->set_ready_for_post_load_tasks(true);
  155. // FIXME: 16. Assert: document's URL and document's relevant settings object's creation URL are about:blank.
  156. // 17. Set document's is initial about:blank to true.
  157. document->set_is_initial_about_blank(true);
  158. // 18. Ensure that document has a single child html node, which itself has two empty child nodes: a head element, and a body element.
  159. auto html_node = document->create_element(HTML::TagNames::html).release_value();
  160. MUST(html_node->append_child(document->create_element(HTML::TagNames::head).release_value()));
  161. MUST(html_node->append_child(document->create_element(HTML::TagNames::body).release_value()));
  162. MUST(document->append_child(html_node));
  163. // 19. Set the active document of browsingContext to document.
  164. browsing_context->set_active_document(*document);
  165. // 20. If browsingContext's creator URL is non-null, then set document's referrer to the serialization of it.
  166. if (browsing_context->m_creator_url.has_value()) {
  167. document->set_referrer(browsing_context->m_creator_url->serialize());
  168. }
  169. // FIXME: 21. If creator is non-null, then set document's policy container to a clone of creator's policy container.
  170. // 22. Append a new session history entry to browsingContext's session history whose URL is about:blank and document is document.
  171. browsing_context->m_session_history.append(HTML::SessionHistoryEntry {
  172. .url = AK::URL("about:blank"),
  173. .document = document.ptr(),
  174. .serialized_state = {},
  175. .policy_container = {},
  176. .scroll_restoration_mode = {},
  177. .browsing_context_name = {},
  178. .original_source_browsing_context = {},
  179. });
  180. // 23. Completely finish loading document.
  181. document->completely_finish_loading();
  182. // 24. Return browsingContext.
  183. return *browsing_context;
  184. }
  185. BrowsingContext::BrowsingContext(Page& page, HTML::BrowsingContextContainer* container)
  186. : m_page(page)
  187. , m_loader(*this)
  188. , m_event_handler({}, *this)
  189. , m_container(container)
  190. {
  191. m_cursor_blink_timer = Platform::Timer::create_repeating(500, [this] {
  192. if (!is_focused_context())
  193. return;
  194. if (m_cursor_position.node() && m_cursor_position.node()->layout_node()) {
  195. m_cursor_blink_state = !m_cursor_blink_state;
  196. m_cursor_position.node()->layout_node()->set_needs_display();
  197. }
  198. });
  199. }
  200. BrowsingContext::~BrowsingContext() = default;
  201. void BrowsingContext::visit_edges(Cell::Visitor& visitor)
  202. {
  203. Base::visit_edges(visitor);
  204. for (auto& entry : m_session_history)
  205. visitor.visit(entry.document);
  206. visitor.visit(m_container);
  207. visitor.visit(m_window_proxy);
  208. visitor.visit(m_opener_browsing_context);
  209. visitor.visit(m_group);
  210. visitor.visit(m_parent);
  211. visitor.visit(m_first_child);
  212. visitor.visit(m_last_child);
  213. visitor.visit(m_next_sibling);
  214. visitor.visit(m_previous_sibling);
  215. }
  216. void BrowsingContext::did_edit(Badge<EditEventHandler>)
  217. {
  218. reset_cursor_blink_cycle();
  219. if (m_cursor_position.node() && is<DOM::Text>(*m_cursor_position.node())) {
  220. auto& text_node = static_cast<DOM::Text&>(*m_cursor_position.node());
  221. if (auto* input_element = text_node.owner_input_element())
  222. input_element->did_edit_text_node({});
  223. }
  224. }
  225. void BrowsingContext::reset_cursor_blink_cycle()
  226. {
  227. m_cursor_blink_state = true;
  228. m_cursor_blink_timer->restart();
  229. if (m_cursor_position.is_valid() && m_cursor_position.node()->layout_node())
  230. m_cursor_position.node()->layout_node()->set_needs_display();
  231. }
  232. // https://html.spec.whatwg.org/multipage/browsers.html#top-level-browsing-context
  233. bool BrowsingContext::is_top_level() const
  234. {
  235. // 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.
  236. return !parent();
  237. }
  238. bool BrowsingContext::is_focused_context() const
  239. {
  240. return m_page && &m_page->focused_context() == this;
  241. }
  242. // https://html.spec.whatwg.org/multipage/browsers.html#set-the-active-document
  243. void BrowsingContext::set_active_document(JS::NonnullGCPtr<DOM::Document> document)
  244. {
  245. auto previously_active_document = active_document();
  246. // 1. Let window be document's relevant global object.
  247. auto& window = verify_cast<HTML::Window>(relevant_global_object(document));
  248. // 2. Set document's visibility state to browsingContext's top-level browsing context's system visibility state.
  249. document->set_visibility_state({}, top_level_browsing_context().system_visibility_state());
  250. // 3. Set browsingContext's active window to window.
  251. m_window_proxy->set_window({}, window);
  252. // 4. Set window's associated Document to document.
  253. window.set_associated_document(document);
  254. // 5. Set window's relevant settings object's execution ready flag.
  255. relevant_settings_object(window).execution_ready = true;
  256. // AD-HOC:
  257. document->set_browsing_context(this);
  258. if (m_page && is_top_level())
  259. m_page->client().page_did_change_title(document->title());
  260. if (previously_active_document && previously_active_document != document.ptr())
  261. previously_active_document->did_stop_being_active_document_in_browsing_context({});
  262. }
  263. void BrowsingContext::set_viewport_rect(CSSPixelRect const& rect)
  264. {
  265. bool did_change = false;
  266. if (m_size != rect.size()) {
  267. m_size = rect.size();
  268. if (auto* document = active_document()) {
  269. // NOTE: Resizing the viewport changes the reference value for viewport-relative CSS lengths.
  270. document->invalidate_style();
  271. document->invalidate_layout();
  272. }
  273. did_change = true;
  274. }
  275. if (m_viewport_scroll_offset != rect.location()) {
  276. m_viewport_scroll_offset = rect.location();
  277. scroll_offset_did_change();
  278. did_change = true;
  279. }
  280. if (did_change) {
  281. for (auto* client : m_viewport_clients)
  282. client->browsing_context_did_set_viewport_rect(rect);
  283. }
  284. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  285. HTML::main_thread_event_loop().schedule();
  286. }
  287. void BrowsingContext::set_size(CSSPixelSize size)
  288. {
  289. if (m_size == size)
  290. return;
  291. m_size = size;
  292. if (auto* document = active_document()) {
  293. document->invalidate_style();
  294. document->invalidate_layout();
  295. }
  296. for (auto* client : m_viewport_clients)
  297. client->browsing_context_did_set_viewport_rect(viewport_rect());
  298. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  299. HTML::main_thread_event_loop().schedule();
  300. }
  301. void BrowsingContext::set_needs_display()
  302. {
  303. set_needs_display(viewport_rect());
  304. }
  305. void BrowsingContext::set_needs_display(CSSPixelRect const& rect)
  306. {
  307. if (!viewport_rect().intersects(rect))
  308. return;
  309. if (is_top_level()) {
  310. if (m_page)
  311. m_page->client().page_did_invalidate(to_top_level_rect(rect));
  312. return;
  313. }
  314. if (container() && container()->layout_node())
  315. container()->layout_node()->set_needs_display();
  316. }
  317. void BrowsingContext::scroll_to(CSSPixelPoint position)
  318. {
  319. if (active_document())
  320. active_document()->force_layout();
  321. if (m_page)
  322. m_page->client().page_did_request_scroll_to(position);
  323. }
  324. void BrowsingContext::scroll_to_anchor(DeprecatedString const& fragment)
  325. {
  326. JS::GCPtr<DOM::Document> document = active_document();
  327. if (!document)
  328. return;
  329. auto element = document->get_element_by_id(fragment);
  330. if (!element) {
  331. auto candidates = document->get_elements_by_name(fragment);
  332. for (auto& candidate : candidates->collect_matching_elements()) {
  333. if (is<HTML::HTMLAnchorElement>(*candidate)) {
  334. element = &verify_cast<HTML::HTMLAnchorElement>(*candidate);
  335. break;
  336. }
  337. }
  338. }
  339. if (!element)
  340. return;
  341. document->force_layout();
  342. if (!element->layout_node())
  343. return;
  344. auto& layout_node = *element->layout_node();
  345. CSSPixelRect target_rect { layout_node.box_type_agnostic_position(), { viewport_rect().width(), viewport_rect().height() } };
  346. if (is<Layout::Box>(layout_node)) {
  347. auto& layout_box = verify_cast<Layout::Box>(layout_node);
  348. auto padding_box = layout_box.box_model().padding_box();
  349. target_rect.translate_by(-padding_box.left, -padding_box.top);
  350. }
  351. if (m_page)
  352. m_page->client().page_did_request_scroll_into_view(target_rect);
  353. }
  354. CSSPixelRect BrowsingContext::to_top_level_rect(CSSPixelRect const& a_rect)
  355. {
  356. auto rect = a_rect;
  357. rect.set_location(to_top_level_position(a_rect.location()));
  358. return rect;
  359. }
  360. CSSPixelPoint BrowsingContext::to_top_level_position(CSSPixelPoint a_position)
  361. {
  362. auto position = a_position;
  363. for (auto ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  364. if (ancestor->is_top_level())
  365. break;
  366. if (!ancestor->container())
  367. return {};
  368. if (!ancestor->container()->layout_node())
  369. return {};
  370. position.translate_by(ancestor->container()->layout_node()->box_type_agnostic_position());
  371. }
  372. return position;
  373. }
  374. void BrowsingContext::set_cursor_position(DOM::Position position)
  375. {
  376. if (m_cursor_position == position)
  377. return;
  378. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  379. m_cursor_position.node()->layout_node()->set_needs_display();
  380. m_cursor_position = move(position);
  381. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  382. m_cursor_position.node()->layout_node()->set_needs_display();
  383. reset_cursor_blink_cycle();
  384. }
  385. static DeprecatedString visible_text_in_range(DOM::Range const& range)
  386. {
  387. // NOTE: This is an adaption of Range stringification, but we skip over DOM nodes that don't have a corresponding layout node.
  388. StringBuilder builder;
  389. if (range.start_container() == range.end_container() && is<DOM::Text>(*range.start_container())) {
  390. if (!range.start_container()->layout_node())
  391. return ""sv;
  392. return static_cast<DOM::Text const&>(*range.start_container()).data().substring(range.start_offset(), range.end_offset() - range.start_offset());
  393. }
  394. if (is<DOM::Text>(*range.start_container()) && range.start_container()->layout_node())
  395. builder.append(static_cast<DOM::Text const&>(*range.start_container()).data().substring_view(range.start_offset()));
  396. for (DOM::Node const* node = range.start_container(); node != range.end_container()->next_sibling(); node = node->next_in_pre_order()) {
  397. if (is<DOM::Text>(*node) && range.contains_node(*node) && node->layout_node())
  398. builder.append(static_cast<DOM::Text const&>(*node).data());
  399. }
  400. if (is<DOM::Text>(*range.end_container()) && range.end_container()->layout_node())
  401. builder.append(static_cast<DOM::Text const&>(*range.end_container()).data().substring_view(0, range.end_offset()));
  402. return builder.to_deprecated_string();
  403. }
  404. DeprecatedString BrowsingContext::selected_text() const
  405. {
  406. auto* document = active_document();
  407. if (!document)
  408. return ""sv;
  409. auto selection = const_cast<DOM::Document&>(*document).get_selection();
  410. auto range = selection->range();
  411. if (!range)
  412. return ""sv;
  413. return visible_text_in_range(*range);
  414. }
  415. void BrowsingContext::select_all()
  416. {
  417. auto* document = active_document();
  418. if (!document)
  419. return;
  420. auto* body = document->body();
  421. if (!body)
  422. return;
  423. auto selection = document->get_selection();
  424. if (!selection)
  425. return;
  426. (void)selection->select_all_children(*document->body());
  427. }
  428. void BrowsingContext::register_viewport_client(ViewportClient& client)
  429. {
  430. auto result = m_viewport_clients.set(&client);
  431. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  432. }
  433. void BrowsingContext::unregister_viewport_client(ViewportClient& client)
  434. {
  435. bool was_removed = m_viewport_clients.remove(&client);
  436. VERIFY(was_removed);
  437. }
  438. void BrowsingContext::register_frame_nesting(AK::URL const& url)
  439. {
  440. m_frame_nesting_levels.ensure(url)++;
  441. }
  442. bool BrowsingContext::is_frame_nesting_allowed(AK::URL const& url) const
  443. {
  444. return m_frame_nesting_levels.get(url).value_or(0) < 3;
  445. }
  446. bool BrowsingContext::increment_cursor_position_offset()
  447. {
  448. if (!m_cursor_position.increment_offset())
  449. return false;
  450. reset_cursor_blink_cycle();
  451. return true;
  452. }
  453. bool BrowsingContext::decrement_cursor_position_offset()
  454. {
  455. if (!m_cursor_position.decrement_offset())
  456. return false;
  457. reset_cursor_blink_cycle();
  458. return true;
  459. }
  460. DOM::Document* BrowsingContext::container_document()
  461. {
  462. if (auto* container = this->container())
  463. return &container->document();
  464. return nullptr;
  465. }
  466. DOM::Document const* BrowsingContext::container_document() const
  467. {
  468. if (auto* container = this->container())
  469. return &container->document();
  470. return nullptr;
  471. }
  472. // https://html.spec.whatwg.org/#rendering-opportunity
  473. bool BrowsingContext::has_a_rendering_opportunity() const
  474. {
  475. // 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,
  476. // accounting for hardware refresh rate constraints and user agent throttling for performance reasons, but considering content presentable even if it's outside the viewport.
  477. // FIXME: We should at the very least say `false` here if we're an inactive browser tab.
  478. return true;
  479. }
  480. // https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-browsing-context
  481. JS::GCPtr<DOM::Node> BrowsingContext::currently_focused_area()
  482. {
  483. // 1. If topLevelBC does not have system focus, then return null.
  484. if (!is_focused_context())
  485. return nullptr;
  486. // 2. Let candidate be topLevelBC's active document.
  487. auto* candidate = active_document();
  488. // 3. While candidate's focused area is a browsing context container with a non-null nested browsing context:
  489. // set candidate to the active document of that browsing context container's nested browsing context.
  490. while (candidate->focused_element()
  491. && is<HTML::BrowsingContextContainer>(candidate->focused_element())
  492. && static_cast<HTML::BrowsingContextContainer&>(*candidate->focused_element()).nested_browsing_context()) {
  493. candidate = static_cast<HTML::BrowsingContextContainer&>(*candidate->focused_element()).nested_browsing_context()->active_document();
  494. }
  495. // 4. If candidate's focused area is non-null, set candidate to candidate's focused area.
  496. if (candidate->focused_element()) {
  497. // NOTE: We return right away here instead of assigning to candidate,
  498. // since that would require compromising type safety.
  499. return candidate->focused_element();
  500. }
  501. // 5. Return candidate.
  502. return candidate;
  503. }
  504. // https://html.spec.whatwg.org/#the-rules-for-choosing-a-browsing-context-given-a-browsing-context-name
  505. BrowsingContext::ChosenBrowsingContext BrowsingContext::choose_a_browsing_context(StringView name, bool no_opener)
  506. {
  507. // The rules for choosing a browsing context, given a browsing context name name, a browsing context current, and
  508. // a boolean noopener are as follows:
  509. // 1. Let chosen be null.
  510. JS::GCPtr<BrowsingContext> chosen = nullptr;
  511. // 2. Let windowType be "existing or none".
  512. auto window_type = WindowType::ExistingOrNone;
  513. // 3. Let sandboxingFlagSet be current's active document's active sandboxing flag set.
  514. auto sandboxing_flag_set = active_document()->active_sandboxing_flag_set();
  515. // 4. If name is the empty string or an ASCII case-insensitive match for "_self", then set chosen to current.
  516. if (name.is_empty() || name.equals_ignoring_case("_self"sv)) {
  517. chosen = this;
  518. }
  519. // 5. Otherwise, if name is an ASCII case-insensitive match for "_parent", set chosen to current's parent browsing
  520. // context, if any, and current otherwise.
  521. else if (name.equals_ignoring_case("_parent"sv)) {
  522. if (auto parent = this->parent())
  523. chosen = parent;
  524. else
  525. chosen = this;
  526. }
  527. // 6. Otherwise, if name is an ASCII case-insensitive match for "_top", set chosen to current's top-level browsing
  528. // context, if any, and current otherwise.
  529. else if (name.equals_ignoring_case("_top"sv)) {
  530. chosen = &top_level_browsing_context();
  531. }
  532. // FIXME: 7. Otherwise, if name is not an ASCII case-insensitive match for "_blank", there exists a browsing context
  533. // whose name is the same as name, current is familiar with that browsing context, and the user agent
  534. // determines that the two browsing contexts are related enough that it is ok if they reach each other,
  535. // set chosen to that browsing context. If there are multiple matching browsing contexts, the user agent
  536. // should set chosen to one in some arbitrary consistent manner, such as the most recently opened, most
  537. // recently focused, or more closely related.
  538. else if (!name.equals_ignoring_case("_blank"sv)) {
  539. dbgln("FIXME: Find matching browser context for name {}", name);
  540. chosen = this;
  541. } else {
  542. // 8. Otherwise, a new browsing context is being requested, and what happens depends on the user agent's
  543. // configuration and abilities — it is determined by the rules given for the first applicable option from
  544. // the following list:
  545. // --> If current's active window does not have transient activation and the user agent has been configured to
  546. // not show popups (i.e., the user agent has a "popup blocker" enabled)
  547. VERIFY(m_page);
  548. if (!active_window()->has_transient_activation() && m_page->should_block_pop_ups()) {
  549. // FIXME: The user agent may inform the user that a popup has been blocked.
  550. dbgln("Pop-up blocked!");
  551. }
  552. // --> If sandboxingFlagSet has the sandboxed auxiliary navigation browsing context flag set
  553. else if (sandboxing_flag_set.flags & SandboxingFlagSet::SandboxedAuxiliaryNavigation) {
  554. // FIXME: The user agent may report to a developer console that a popup has been blocked.
  555. dbgln("Pop-up blocked!");
  556. }
  557. // --> If the user agent has been configured such that in this instance it will create a new browsing context
  558. else if (true) { // FIXME: When is this the case?
  559. // 1. Set windowType to "new and unrestricted".
  560. window_type = WindowType::NewAndUnrestricted;
  561. // 2. If current's top-level browsing context's active document's cross-origin opener policy's value is
  562. // "same-origin" or "same-origin-plus-COEP", then:
  563. 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) {
  564. // 1. Let currentDocument be current's active document.
  565. auto* current_document = top_level_browsing_context().active_document();
  566. // 2. If currentDocument's origin is not same origin with currentDocument's relevant settings object's
  567. // top-level origin, then set noopener to true, name to "_blank", and windowType to "new with no opener".
  568. if (!current_document->origin().is_same_origin(current_document->relevant_settings_object().top_level_origin)) {
  569. no_opener = true;
  570. name = "_blank"sv;
  571. window_type = WindowType::NewWithNoOpener;
  572. }
  573. }
  574. // 3. If noopener is true, then set chosen to the result of creating a new top-level browsing context.
  575. if (no_opener) {
  576. chosen = HTML::BrowsingContext::create_a_new_top_level_browsing_context(*m_page);
  577. }
  578. // 4. Otherwise:
  579. else {
  580. // 1. Set chosen to the result of creating a new auxiliary browsing context with current.
  581. // FIXME: We have no concept of auxiliary browsing context
  582. chosen = HTML::BrowsingContext::create_a_new_top_level_browsing_context(*m_page);
  583. // 2. If sandboxingFlagSet's sandboxed navigation browsing context flag is set, then current must be
  584. // set as chosen's one permitted sandboxed navigator.
  585. // FIXME: We have no concept of one permitted sandboxed navigator
  586. }
  587. // 5. If sandboxingFlagSet's sandbox propagates to auxiliary browsing contexts flag is set, then all the
  588. // flags that are set in sandboxingFlagSet must be set in chosen's popup sandboxing flag set.
  589. // FIXME: Our BrowsingContexts do not have SandboxingFlagSets yet, only documents do
  590. // 6. If name is not an ASCII case-insensitive match for "_blank", then set chosen's name to name.
  591. if (!name.equals_ignoring_case("_blank"sv))
  592. chosen->set_name(name);
  593. }
  594. // --> If the user agent has been configured such that in this instance t will reuse current
  595. else if (false) { // FIXME: When is this the case?
  596. // Set chosen to current.
  597. chosen = *this;
  598. }
  599. // --> If the user agent has been configured such that in this instance it will not find a browsing context
  600. else if (false) { // FIXME: When is this the case?
  601. // Do nothing.
  602. }
  603. }
  604. // 9. Return chosen and windowType.
  605. return { chosen, window_type };
  606. }
  607. // https://html.spec.whatwg.org/multipage/browsers.html#document-tree-child-browsing-context
  608. size_t BrowsingContext::document_tree_child_browsing_context_count() const
  609. {
  610. size_t count = 0;
  611. // A browsing context child is a document-tree child browsing context of parent if child is a child browsing context and child's container is in a document tree.
  612. for_each_child([this, &count](BrowsingContext const& child) {
  613. if (child.is_child_of(*this) && child.container()->in_a_document_tree())
  614. ++count;
  615. });
  616. return count;
  617. }
  618. // https://html.spec.whatwg.org/multipage/browsers.html#child-browsing-context
  619. bool BrowsingContext::is_child_of(BrowsingContext const& parent) const
  620. {
  621. // A browsing context child is said to be a child browsing context of another browsing context parent,
  622. // if child's container document is non-null and child's container document's browsing context is parent.
  623. return container_document() && container_document()->browsing_context() == &parent;
  624. }
  625. // https://html.spec.whatwg.org/multipage/dom.html#still-on-its-initial-about:blank-document
  626. bool BrowsingContext::still_on_its_initial_about_blank_document() const
  627. {
  628. // A browsing context browsingContext is still on its initial about:blank Document
  629. // if browsingContext's session history's size is 1
  630. // and browsingContext's session history[0]'s document's is initial about:blank is true.
  631. return m_session_history.size() == 1
  632. && m_session_history[0].document
  633. && m_session_history[0].document->is_initial_about_blank();
  634. }
  635. DOM::Document const* BrowsingContext::active_document() const
  636. {
  637. auto* window = active_window();
  638. if (!window)
  639. return nullptr;
  640. return &window->associated_document();
  641. }
  642. DOM::Document* BrowsingContext::active_document()
  643. {
  644. auto* window = active_window();
  645. if (!window)
  646. return nullptr;
  647. return &window->associated_document();
  648. }
  649. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  650. HTML::Window* BrowsingContext::active_window()
  651. {
  652. return m_window_proxy->window();
  653. }
  654. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  655. HTML::Window const* BrowsingContext::active_window() const
  656. {
  657. return m_window_proxy->window();
  658. }
  659. HTML::WindowProxy* BrowsingContext::window_proxy()
  660. {
  661. return m_window_proxy.ptr();
  662. }
  663. HTML::WindowProxy const* BrowsingContext::window_proxy() const
  664. {
  665. return m_window_proxy.ptr();
  666. }
  667. void BrowsingContext::scroll_offset_did_change()
  668. {
  669. // https://w3c.github.io/csswg-drafts/cssom-view-1/#scrolling-events
  670. // Whenever a viewport gets scrolled (whether in response to user interaction or by an API), the user agent must run these steps:
  671. // 1. Let doc be the viewport’s associated Document.
  672. auto* doc = active_document();
  673. VERIFY(doc);
  674. // 2. If doc is already in doc’s pending scroll event targets, abort these steps.
  675. for (auto& target : doc->pending_scroll_event_targets()) {
  676. if (target.ptr() == doc)
  677. return;
  678. }
  679. // 3. Append doc to doc’s pending scroll event targets.
  680. doc->pending_scroll_event_targets().append(*doc);
  681. }
  682. BrowsingContextGroup* BrowsingContext::group()
  683. {
  684. return m_group;
  685. }
  686. void BrowsingContext::set_group(BrowsingContextGroup* group)
  687. {
  688. m_group = group;
  689. }
  690. // https://html.spec.whatwg.org/multipage/browsers.html#bcg-remove
  691. void BrowsingContext::remove()
  692. {
  693. // 1. Assert: browsingContext's group is non-null, because a browsing context only gets discarded once.
  694. VERIFY(group());
  695. // 2. Let group be browsingContext's group.
  696. JS::NonnullGCPtr<BrowsingContextGroup> group = *this->group();
  697. // 3. Set browsingContext's group to null.
  698. set_group(nullptr);
  699. // 4. Remove browsingContext from group's browsing context set.
  700. group->browsing_context_set().remove(this);
  701. // 5. If group's browsing context set is empty, then remove group from the user agent's browsing context group set.
  702. // NOTE: This is done by ~BrowsingContextGroup() when the refcount reaches 0.
  703. }
  704. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
  705. WebIDL::ExceptionOr<void> BrowsingContext::navigate(
  706. JS::NonnullGCPtr<Fetch::Infrastructure::Request> resource,
  707. BrowsingContext& source_browsing_context,
  708. bool exceptions_enabled,
  709. HistoryHandlingBehavior history_handling,
  710. Optional<PolicyContainer> history_policy_container,
  711. DeprecatedString navigation_type,
  712. Optional<DeprecatedString> navigation_id,
  713. Function<void(JS::NonnullGCPtr<Fetch::Infrastructure::Response>)> process_response_end_of_body)
  714. {
  715. // 1. If resource is a URL, then set resource to a new request whose URL is resource.
  716. // NOTE: This function only accepts resources that are already a request, so this is irrelevant.
  717. // 2. If resource is a request and historyHandling is "reload", then set resource's reload-navigation flag.
  718. if (history_handling == HistoryHandlingBehavior::Reload)
  719. resource->set_reload_navigation(true);
  720. // 3. If the source browsing context is not allowed to navigate browsingContext, then:
  721. if (!source_browsing_context.is_allowed_to_navigate(*this)) {
  722. // 1. If exceptionsEnabled is given and is true, then throw a "SecurityError" DOMException.
  723. if (exceptions_enabled) {
  724. VERIFY(source_browsing_context.active_document());
  725. return WebIDL::SecurityError::create(source_browsing_context.active_document()->realm(), "Source browsing context not allowed to navigate"sv);
  726. }
  727. // FIXME: 2. Otherwise, the user agent may instead offer to open resource in a new top-level browsing context
  728. // or in the top-level browsing context of the source browsing context, at the user's option,
  729. // in which case the user agent must navigate that designated top-level browsing context
  730. // to resource as if the user had requested it independently.
  731. }
  732. // 4. If navigationId is null:
  733. if (!navigation_id.has_value()) {
  734. // 1. If historyHandling is "reload", and browsingContext's active document's navigation id is not null,
  735. if (history_handling == HistoryHandlingBehavior::Reload && active_document()->navigation_id().has_value()) {
  736. // let navigationId be browsingContext's active document's navigation id.
  737. navigation_id = active_document()->navigation_id();
  738. } else {
  739. // Otherwise let navigation id be the result of generating a random UUID. [UUID]
  740. // FIXME: Generate a UUID.
  741. navigation_id = "FIXME";
  742. }
  743. }
  744. // FIXME: 5. If browsingContext's active document's unload counter is greater than 0,
  745. // then invoke WebDriver BiDi navigation failed
  746. // with a WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is resource's url
  747. // and return.
  748. // 6. If historyHandling is "default", and any of the following are true:
  749. // - browsingContext is still on its initial about:blank Document
  750. // - resource is a request whose URL equals browsingContext's active document's URL
  751. // - resource is a request whose URL's scheme is "javascript"
  752. if (history_handling == HistoryHandlingBehavior::Default
  753. && (still_on_its_initial_about_blank_document()
  754. || resource->url().equals(active_document()->url())
  755. || resource->url().scheme() == "javascript"sv)) {
  756. // then set historyHandling to "replace".
  757. history_handling = HistoryHandlingBehavior::Replace;
  758. }
  759. // 7. If historyHandling is not "reload", resource is a request,
  760. // resource's URL equals browsingContext's active document's URL with exclude fragments set to true,
  761. // and resource's URL's fragment is non-null, then:
  762. if (history_handling != HistoryHandlingBehavior::Reload
  763. && resource->url().equals(active_document()->url(), AK::URL::ExcludeFragment::Yes)
  764. && !resource->url().fragment().is_null()) {
  765. // 1. Navigate to a fragment given browsingContext, resource's URL, historyHandling, and navigationId.
  766. TRY(navigate_to_a_fragment(resource->url(), history_handling, *navigation_id));
  767. // 2. Return.
  768. return {};
  769. }
  770. // FIXME: 8. Let incumbentNavigationOrigin be the origin of the incumbent settings object,
  771. // or if no script was involved, the origin of the node document of the element that initiated the navigation.
  772. // FIXME: 9. Let initiatorPolicyContainer be a clone of the source browsing context's active document's policy container.
  773. // FIXME: 10. If resource is a request, then set resource's policy container to initiatorPolicyContainer.
  774. // FIXME: 11. Cancel any preexisting but not yet mature attempt to navigate browsingContext,
  775. // including canceling any instances of the fetch algorithm started by those attempts.
  776. // If one of those attempts has already created and initialized a new Document object,
  777. // abort that Document also.
  778. // (Navigation attempts that have matured already have session history entries,
  779. // and are therefore handled during the update the session history with the new page algorithm, later.)
  780. // FIXME: 12. Let unloadPromptResult be the result of calling prompt to unload with the active document of browsingContext.
  781. // If this instance of the navigation algorithm gets canceled while this step is running,
  782. // the prompt to unload algorithm must nonetheless be run to completion.
  783. // FIXME: 13. If unloadPromptResult is "refuse", then return a new WebDriver BiDi navigation status whose id is navigationId and status is "canceled".
  784. // 14. Abort the active document of browsingContext.
  785. active_document()->abort();
  786. // FIXME: 15. If browsingContext is a child browsing context, then put it in the delaying load events mode.
  787. // The user agent must take this child browsing context out of the delaying load events mode when this navigation algorithm later matures,
  788. // or when it terminates (whether due to having run all the steps, or being canceled, or being aborted),
  789. // whichever happens first.
  790. // FIXME: 16. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and browsingContext's container.
  791. // FIXME: 17. Let allowedToDownload be the result of running the allowed to download algorithm given the source browsing context and browsingContext.
  792. // 18. Let hasTransientActivation be true if the source browsing context's active window has transient activation; otherwise false.
  793. [[maybe_unused]] bool has_transient_activation = source_browsing_context.active_window()->has_transient_activation();
  794. // FIXME: 19. Invoke WebDriver BiDi navigation started with browsingContext, and a new WebDriver BiDi navigation status whose id is navigationId, url is resource's url, and status is "pending".
  795. // 20. Return, and continue running these steps in parallel.
  796. // FIXME: Implement the rest of this algorithm
  797. (void)history_policy_container;
  798. (void)navigation_type;
  799. (void)process_response_end_of_body;
  800. // AD-HOC:
  801. loader().load(resource->url(), FrameLoader::Type::IFrame);
  802. return {};
  803. }
  804. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate-fragid
  805. WebIDL::ExceptionOr<void> BrowsingContext::navigate_to_a_fragment(AK::URL const& url, HistoryHandlingBehavior history_handling, DeprecatedString navigation_id)
  806. {
  807. // 1. If historyHandling is not "replace",
  808. if (history_handling != HistoryHandlingBehavior::Replace) {
  809. // FIXME: then remove all the entries in browsingContext's session history after the current entry.
  810. // (If the current entry is the last entry in the session history, then no entries are removed.)
  811. }
  812. // 2. Remove any tasks queued by the history traversal task source that are associated with any Document objects
  813. // in browsingContext's top-level browsing context's document family.
  814. HTML::main_thread_event_loop().task_queue().remove_tasks_matching([&](HTML::Task const& task) {
  815. return task.source() == Task::Source::HistoryTraversal
  816. && task.document()
  817. && top_level_browsing_context().document_family_contains(*task.document());
  818. });
  819. // 3. Append a new session history entry to the session history whose URL is url,
  820. // document is the current entry's document,
  821. // policy container is the current entry's policy-container
  822. // and scroll restoration mode is the current entry's scroll restoration mode.
  823. m_session_history.append(SessionHistoryEntry {
  824. .url = url,
  825. .document = current_entry().document,
  826. .serialized_state = {},
  827. .policy_container = current_entry().policy_container,
  828. .scroll_restoration_mode = current_entry().scroll_restoration_mode,
  829. .browsing_context_name = {},
  830. .original_source_browsing_context = {},
  831. });
  832. // 4. Traverse the history to the new entry, with historyHandling set to historyHandling.
  833. // This will scroll to the fragment given in what is now the document's URL.
  834. TRY(traverse_the_history(m_session_history.size() - 1, history_handling));
  835. // FIXME: 5. Invoke WebDriver BiDi fragment navigated with browsingContext,
  836. // and a new WebDriver BiDi navigation status whose id is navigationId, url is resource's url, and status is "complete".
  837. (void)navigation_id;
  838. return {};
  839. }
  840. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#traverse-the-history
  841. WebIDL::ExceptionOr<void> BrowsingContext::traverse_the_history(size_t entry_index, HistoryHandlingBehavior history_handling, bool explicit_history_navigation)
  842. {
  843. auto* entry = &m_session_history[entry_index];
  844. // 1. If entry's document is null, then:
  845. if (!entry->document) {
  846. // 1. Assert: historyHandling is "default".
  847. VERIFY(history_handling == HistoryHandlingBehavior::Default);
  848. // 2. Let request be a new request whose URL is entry's URL.
  849. auto& vm = Bindings::main_thread_vm();
  850. auto request = Fetch::Infrastructure::Request::create(vm);
  851. request->set_url(entry->url);
  852. // 3. If explicitHistoryNavigation is true, then set request's history-navigation flag.
  853. if (explicit_history_navigation)
  854. request->set_history_navigation(true);
  855. // 4. Navigate the browsing context to request with historyHandling set to "entry update"
  856. // and with historyPolicyContainer set to entry's policy container.
  857. // The navigation must be done using the same source browsing context as was used the first time entry was created.
  858. VERIFY(entry->original_source_browsing_context);
  859. TRY(navigate(request, *entry->original_source_browsing_context, false, HistoryHandlingBehavior::EntryUpdate, entry->policy_container));
  860. // 5. Return.
  861. return {};
  862. }
  863. // FIXME: 2. Save persisted state to the current entry.
  864. // 3. Let newDocument be entry's document.
  865. JS::GCPtr<DOM::Document> new_document = entry->document.ptr();
  866. // 4. Assert: newDocument's is initial about:blank is false,
  867. // i.e., we never traverse back to the initial about:blank Document because it always gets replaced when we navigate away from it.
  868. VERIFY(!new_document->is_initial_about_blank());
  869. // 5. If newDocument is different than the current entry's document, or historyHandling is "entry update" or "reload", then:
  870. if (new_document.ptr() != current_entry().document.ptr()
  871. || history_handling == HistoryHandlingBehavior::EntryUpdate) {
  872. // FIXME: 1. If newDocument's suspended timer handles is not empty:
  873. // FIXME: 1. Assert: newDocument's suspension time is not zero.
  874. // FIXME: 2. Let suspendDuration be the current high resolution time minus newDocument's suspension time.
  875. // FIXME: 3. Let activeTimers be newDocument's relevant global object's map of active timers.
  876. // FIXME: 4. For each handle in newDocument's suspended timer handles, if activeTimers[handle] exists, then increase activeTimers[handle] by suspendDuration.
  877. }
  878. // 2. Remove any tasks queued by the history traversal task source
  879. // that are associated with any Document objects in the top-level browsing context's document family.
  880. HTML::main_thread_event_loop().task_queue().remove_tasks_matching([&](HTML::Task const& task) {
  881. return task.source() == Task::Source::HistoryTraversal
  882. && task.document()
  883. && top_level_browsing_context().document_family_contains(*task.document());
  884. });
  885. // 3. If newDocument's origin is not same origin with the current entry's document's origin, then:
  886. if (!new_document->origin().is_same_origin(current_entry().document->origin())) {
  887. // FIXME: 1. Let entriesToUpdate be all entries in the session history whose document's origin is same origin as the active document
  888. // and that are contiguous with the current entry.
  889. // FIXME: 2. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to the current browsing context name.
  890. // FIXME: 3. If the browsing context is a top-level browsing context, but not an auxiliary browsing context whose disowned is false, then set the browsing context's name to the empty string.
  891. }
  892. // 4. Set the active document of the browsing context to newDocument.
  893. set_active_document(*new_document);
  894. // 5. If entry's browsing context name is not null, then:
  895. if (entry->browsing_context_name.has_value()) {
  896. // 1. Set the browsing context's name to entry's browsing context name.
  897. m_name = *entry->browsing_context_name;
  898. // FIXME: 2. Let entriesToUpdate be all entries in the session history whose document's origin is same origin as the new active document's origin and that are contiguous with entry.
  899. // FIXME: 3. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to null.
  900. }
  901. // FIXME: 6. If newDocument has any form controls whose autofill field name is "off", invoke the reset algorithm of each of those elements.
  902. // 7. If newDocument's current document readiness "complete",
  903. if (new_document->ready_state() == "complete"sv) {
  904. // then queue a global task on the DOM manipulation task source given newDocument's relevant global object to run the following steps:
  905. queue_global_task(Task::Source::DOMManipulation, relevant_global_object(*new_document), [new_document] {
  906. // 1. If newDocument's page showing flag is true, then abort these steps.
  907. if (new_document->page_showing())
  908. return;
  909. // 2. Set newDocument's page showing flag to true.
  910. new_document->set_page_showing(true);
  911. // 3. Update the visibility state of newDocument to "hidden".
  912. new_document->update_the_visibility_state(VisibilityState::Hidden);
  913. // 4. Fire a page transition event named pageshow at newDocument's relevant global object with true.
  914. auto& window = verify_cast<HTML::Window>(relevant_global_object(*new_document));
  915. window.fire_a_page_transition_event(HTML::EventNames::pageshow, true);
  916. });
  917. }
  918. // 6. Set newDocument's URL to entry's URL.
  919. new_document->set_url(entry->url);
  920. // 7. Let hashChanged be false, and let oldURL and newURL be null.
  921. bool hash_changed = false;
  922. Optional<AK::URL> old_url;
  923. Optional<AK::URL> new_url;
  924. // 8. If entry's URL's fragment is not identical to the current entry's URL's fragment,
  925. // and entry's document equals the current entry's document,
  926. if (entry->url.fragment() != current_entry().url.fragment()
  927. && entry->document.ptr() == current_entry().document.ptr()) {
  928. // then set hashChanged to true, set oldURL to the current entry's URL, and set newURL to entry's URL.
  929. hash_changed = true;
  930. old_url = current_entry().url;
  931. new_url = entry->url;
  932. }
  933. // 9. If historyHandling is "replace", then remove the entry immediately before entry in the session history.
  934. if (history_handling == HistoryHandlingBehavior::Replace) {
  935. // FIXME: This is gnarly.
  936. m_session_history.remove(entry_index - 1);
  937. entry_index--;
  938. entry = &m_session_history[entry_index];
  939. }
  940. // 10. If entry's persisted user state is null, and its URL's fragment is non-null, then scroll to the fragment.
  941. if (!entry->url.fragment().is_null()) {
  942. // FIXME: Implement the full "scroll to the fragment" algorithm:
  943. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#scroll-to-the-fragment-identifier
  944. scroll_to_anchor(entry->url.fragment());
  945. }
  946. // 11. Set the current entry to entry.
  947. m_session_history_index = entry_index;
  948. // 12. Let targetRealm be the current Realm Record.
  949. auto* target_realm = Bindings::main_thread_vm().current_realm();
  950. VERIFY(target_realm);
  951. // FIXME: 13. Let state be null.
  952. // FIXME: 14. If entry's serialized state is not null, then set state to StructuredDeserialize(entry's serialized state, targetRealm).
  953. // If this throws an exception, catch it and ignore the exception.
  954. // FIXME: 15. Set newDocument's History object's state to state.
  955. // FIXME: 16. Let stateChanged be true if newDocument has a latest entry, and that entry is not entry; otherwise let it be false.
  956. // FIXME: 17. Set newDocument's latest entry to entry.
  957. // FIXME: 18. If stateChanged is true, then fire an event named popstate at newDocument's relevant global object, using PopStateEvent, with the state attribute initialized to state.
  958. // FIXME: 19. Restore persisted state from entry.
  959. // 20. If hashChanged is true,
  960. if (hash_changed) {
  961. // then queue a global task on the DOM manipulation task source given newDocument's relevant global object
  962. queue_global_task(Task::Source::DOMManipulation, relevant_global_object(*new_document), [new_document] {
  963. // to fire an event named hashchange at newDocument's relevant global object,
  964. // using HashChangeEvent, with the oldURL attribute initialized to oldURL
  965. // and the newURL attribute initialized to newURL.
  966. // FIXME: Implement a proper HashChangeEvent class.
  967. auto event = DOM::Event::create(verify_cast<HTML::Window>(relevant_global_object(*new_document)).realm(), HTML::EventNames::hashchange).release_value_but_fixme_should_propagate_errors();
  968. new_document->dispatch_event(event);
  969. });
  970. }
  971. return {};
  972. }
  973. // https://html.spec.whatwg.org/multipage/browsers.html#allowed-to-navigate
  974. bool BrowsingContext::is_allowed_to_navigate(BrowsingContext const& other) const
  975. {
  976. VERIFY(active_window());
  977. VERIFY(active_document());
  978. // 1. If A is not the same browsing context as B,
  979. // and A is not one of the ancestor browsing contexts of B,
  980. // and B is not a top-level browsing context,
  981. // FIXME: and A's active document's active sandboxing flag set has its sandboxed navigation browsing context flag set,
  982. // then return false.
  983. if (this != &other
  984. && !this->is_ancestor_of(other)
  985. && !other.is_top_level()) {
  986. return false;
  987. }
  988. // 2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, then:
  989. if (other.is_top_level() && other.is_ancestor_of(*this)) {
  990. // 1. If A's active window has transient activation
  991. // and A's active document's active sandboxing flag set has its sandboxed top-level navigation with user activation browsing context flag set,
  992. // then return false.
  993. if (active_window()->has_transient_activation()
  994. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedTopLevelNavigationWithUserActivation) {
  995. return false;
  996. }
  997. // 2. Otherwise, if A's active window does not have transient activation
  998. // and A's active document's active sandboxing flag set has its sandboxed top-level navigation without user activation browsing context flag set,
  999. // then return false.
  1000. if (!active_window()->has_transient_activation()
  1001. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedTopLevelNavigationWithoutUserActivation) {
  1002. return false;
  1003. }
  1004. }
  1005. // 3. Otherwise, if B is a top-level browsing context,
  1006. // and is neither A nor one of the ancestor browsing contexts of A,
  1007. // and A's Document's active sandboxing flag set has its sandboxed navigation browsing context flag set,
  1008. // and A is not the one permitted sandboxed navigator of B,
  1009. // then return false.
  1010. if (other.is_top_level()
  1011. && &other != this
  1012. && !other.is_ancestor_of(*this)
  1013. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedNavigation
  1014. && this != other.the_one_permitted_sandboxed_navigator()) {
  1015. return false;
  1016. }
  1017. // 4. Return true.
  1018. return true;
  1019. }
  1020. // https://html.spec.whatwg.org/multipage/origin.html#one-permitted-sandboxed-navigator
  1021. BrowsingContext const* BrowsingContext::the_one_permitted_sandboxed_navigator() const
  1022. {
  1023. // FIXME: Implement this.
  1024. return nullptr;
  1025. }
  1026. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  1027. Vector<JS::Handle<DOM::Document>> BrowsingContext::document_family() const
  1028. {
  1029. HashTable<DOM::Document*> documents;
  1030. for (auto& entry : m_session_history) {
  1031. if (!entry.document)
  1032. continue;
  1033. if (documents.set(const_cast<DOM::Document*>(entry.document.ptr())) == AK::HashSetResult::ReplacedExistingEntry)
  1034. continue;
  1035. for (auto& context : entry.document->list_of_descendant_browsing_contexts()) {
  1036. for (auto& document : context->document_family()) {
  1037. documents.set(document.ptr());
  1038. }
  1039. }
  1040. }
  1041. Vector<JS::Handle<DOM::Document>> family;
  1042. for (auto* document : documents) {
  1043. family.append(*document);
  1044. }
  1045. return family;
  1046. }
  1047. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  1048. bool BrowsingContext::document_family_contains(DOM::Document const& document) const
  1049. {
  1050. return document_family().first_matching([&](auto& entry) { return entry.ptr() == &document; }).has_value();
  1051. }
  1052. VisibilityState BrowsingContext::system_visibility_state() const
  1053. {
  1054. return m_system_visibility_state;
  1055. }
  1056. // https://html.spec.whatwg.org/multipage/interaction.html#system-visibility-state
  1057. void BrowsingContext::set_system_visibility_state(VisibilityState visibility_state)
  1058. {
  1059. if (m_system_visibility_state == visibility_state)
  1060. return;
  1061. m_system_visibility_state = visibility_state;
  1062. // When a user-agent determines that the system visibility state for top-level browsing context context
  1063. // has changed to newState, it must queue a task on the user interaction task source to update
  1064. // the visibility state of all the Document objects in the top-level browsing context's document family with newState.
  1065. auto document_family = top_level_browsing_context().document_family();
  1066. queue_global_task(Task::Source::UserInteraction, Bindings::main_thread_vm().current_realm()->global_object(), [visibility_state, document_family = move(document_family)] {
  1067. for (auto& document : document_family) {
  1068. document->update_the_visibility_state(visibility_state);
  1069. }
  1070. });
  1071. }
  1072. // https://html.spec.whatwg.org/multipage/window-object.html#a-browsing-context-is-discarded
  1073. void BrowsingContext::discard()
  1074. {
  1075. m_has_been_discarded = true;
  1076. // 1. Discard all Document objects for all the entries in browsingContext's session history.
  1077. for (auto& entry : m_session_history) {
  1078. if (entry.document)
  1079. entry.document->discard();
  1080. }
  1081. // AD-HOC:
  1082. // FIXME: This should be in the session history!
  1083. if (auto* document = active_document())
  1084. document->discard();
  1085. // 2. If browsingContext is a top-level browsing context, then remove browsingContext.
  1086. if (is_top_level())
  1087. remove();
  1088. // AD-HOC:
  1089. if (parent())
  1090. parent()->remove_child(*this);
  1091. }
  1092. // https://html.spec.whatwg.org/multipage/window-object.html#close-a-browsing-context
  1093. void BrowsingContext::close()
  1094. {
  1095. VERIFY(active_document());
  1096. // FIXME: 1. If the result of calling prompt to unload with browsingContext's active document is "refuse", then return.
  1097. // 2. Unload browsingContext's active document.
  1098. active_document()->unload();
  1099. // 3. Remove browsingContext from the user interface (e.g., close or hide its tab in a tabbed browser).
  1100. if (m_page)
  1101. m_page->client().page_did_close_browsing_context(*this);
  1102. // 4. Discard browsingContext.
  1103. discard();
  1104. }
  1105. void BrowsingContext::append_child(JS::NonnullGCPtr<BrowsingContext> child)
  1106. {
  1107. VERIFY(!child->m_parent);
  1108. if (m_last_child)
  1109. m_last_child->m_next_sibling = child;
  1110. child->m_previous_sibling = m_last_child;
  1111. child->m_parent = this;
  1112. m_last_child = child;
  1113. if (!m_first_child)
  1114. m_first_child = m_last_child;
  1115. }
  1116. void BrowsingContext::remove_child(JS::NonnullGCPtr<BrowsingContext> child)
  1117. {
  1118. VERIFY(child->m_parent.ptr() == this);
  1119. if (m_first_child == child)
  1120. m_first_child = child->m_next_sibling;
  1121. if (m_last_child == child)
  1122. m_last_child = child->m_previous_sibling;
  1123. if (child->m_next_sibling)
  1124. child->m_next_sibling->m_previous_sibling = child->m_previous_sibling;
  1125. if (child->m_previous_sibling)
  1126. child->m_previous_sibling->m_next_sibling = child->m_next_sibling;
  1127. child->m_next_sibling = nullptr;
  1128. child->m_previous_sibling = nullptr;
  1129. child->m_parent = nullptr;
  1130. }
  1131. JS::GCPtr<BrowsingContext> BrowsingContext::first_child() const
  1132. {
  1133. return m_first_child;
  1134. }
  1135. JS::GCPtr<BrowsingContext> BrowsingContext::next_sibling() const
  1136. {
  1137. return m_next_sibling;
  1138. }
  1139. bool BrowsingContext::is_ancestor_of(BrowsingContext const& other) const
  1140. {
  1141. for (auto ancestor = other.parent(); ancestor; ancestor = ancestor->parent()) {
  1142. if (ancestor == this)
  1143. return true;
  1144. }
  1145. return false;
  1146. }
  1147. }