BrowsingContext.cpp 61 KB

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