BrowsingContext.cpp 61 KB

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