BrowsingContext.cpp 55 KB

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