BrowsingContext.cpp 64 KB

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