HTMLLinkElement.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, the SerenityOS developers.
  4. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
  5. * Copyright (c) 2023, Srikavin Ramkumar <me@srikavin.me>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/ByteBuffer.h>
  10. #include <AK/Debug.h>
  11. #include <AK/URL.h>
  12. #include <LibWeb/CSS/Parser/Parser.h>
  13. #include <LibWeb/DOM/Document.h>
  14. #include <LibWeb/DOM/Event.h>
  15. #include <LibWeb/Fetch/Fetching/Fetching.h>
  16. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  17. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  18. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  19. #include <LibWeb/HTML/EventNames.h>
  20. #include <LibWeb/HTML/HTMLLinkElement.h>
  21. #include <LibWeb/HTML/PotentialCORSRequest.h>
  22. #include <LibWeb/Infra/CharacterTypes.h>
  23. #include <LibWeb/Loader/ResourceLoader.h>
  24. #include <LibWeb/Page/Page.h>
  25. #include <LibWeb/Platform/ImageCodecPlugin.h>
  26. namespace Web::HTML {
  27. HTMLLinkElement::HTMLLinkElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  28. : HTMLElement(document, move(qualified_name))
  29. {
  30. }
  31. HTMLLinkElement::~HTMLLinkElement() = default;
  32. JS::ThrowCompletionOr<void> HTMLLinkElement::initialize(JS::Realm& realm)
  33. {
  34. MUST_OR_THROW_OOM(Base::initialize(realm));
  35. set_prototype(&Bindings::ensure_web_prototype<Bindings::HTMLLinkElementPrototype>(realm, "HTMLLinkElement"));
  36. return {};
  37. }
  38. void HTMLLinkElement::inserted()
  39. {
  40. HTMLElement::inserted();
  41. // FIXME: Handle alternate stylesheets properly
  42. if (m_relationship & Relationship::Stylesheet && !(m_relationship & Relationship::Alternate)) {
  43. // https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:fetch-and-process-the-linked-resource
  44. // The appropriate times to fetch and process this type of link are:
  45. // - When the external resource link is created on a link element that is already browsing-context connected.
  46. // - When the external resource link's link element becomes browsing-context connected.
  47. fetch_and_process_linked_resource();
  48. }
  49. // FIXME: Follow spec for fetching and processing these attributes as well
  50. if (m_relationship & Relationship::Preload) {
  51. // FIXME: Respect the "as" attribute.
  52. LoadRequest request;
  53. request.set_url(document().parse_url(attribute(HTML::AttributeNames::href)));
  54. set_resource(ResourceLoader::the().load_resource(Resource::Type::Generic, request));
  55. } else if (m_relationship & Relationship::DNSPrefetch) {
  56. ResourceLoader::the().prefetch_dns(document().parse_url(attribute(HTML::AttributeNames::href)));
  57. } else if (m_relationship & Relationship::Preconnect) {
  58. ResourceLoader::the().preconnect(document().parse_url(attribute(HTML::AttributeNames::href)));
  59. } else if (m_relationship & Relationship::Icon) {
  60. auto favicon_url = document().parse_url(href());
  61. auto favicon_request = LoadRequest::create_for_url_on_page(favicon_url, document().page());
  62. set_resource(ResourceLoader::the().load_resource(Resource::Type::Generic, favicon_request));
  63. }
  64. }
  65. bool HTMLLinkElement::has_loaded_icon() const
  66. {
  67. return m_relationship & Relationship::Icon && resource() && resource()->is_loaded() && resource()->has_encoded_data();
  68. }
  69. void HTMLLinkElement::parse_attribute(DeprecatedFlyString const& name, DeprecatedString const& value)
  70. {
  71. // 4.6.7 Link types - https://html.spec.whatwg.org/multipage/links.html#linkTypes
  72. if (name == HTML::AttributeNames::rel) {
  73. m_relationship = 0;
  74. // Keywords are always ASCII case-insensitive, and must be compared as such.
  75. auto lowercased_value = value.to_lowercase();
  76. // To determine which link types apply to a link, a, area, or form element,
  77. // the element's rel attribute must be split on ASCII whitespace.
  78. // The resulting tokens are the keywords for the link types that apply to that element.
  79. auto parts = lowercased_value.split_view(Infra::is_ascii_whitespace);
  80. for (auto& part : parts) {
  81. if (part == "stylesheet"sv)
  82. m_relationship |= Relationship::Stylesheet;
  83. else if (part == "alternate"sv)
  84. m_relationship |= Relationship::Alternate;
  85. else if (part == "preload"sv)
  86. m_relationship |= Relationship::Preload;
  87. else if (part == "dns-prefetch"sv)
  88. m_relationship |= Relationship::DNSPrefetch;
  89. else if (part == "preconnect"sv)
  90. m_relationship |= Relationship::Preconnect;
  91. else if (part == "icon"sv)
  92. m_relationship |= Relationship::Icon;
  93. }
  94. }
  95. if (m_relationship & Relationship::Stylesheet) {
  96. if (name == HTML::AttributeNames::disabled && m_loaded_style_sheet)
  97. document().style_sheets().remove_sheet(*m_loaded_style_sheet);
  98. // https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:fetch-and-process-the-linked-resource
  99. // The appropriate times to fetch and process this type of link are:
  100. if (
  101. // AD-HOC: When the rel attribute changes
  102. name == AttributeNames::rel ||
  103. // - When the href attribute of the link element of an external resource link that is already browsing-context connected is changed.
  104. name == AttributeNames::href ||
  105. // - When the disabled attribute of the link element of an external resource link that is already browsing-context connected is set, changed, or removed.
  106. name == AttributeNames::disabled ||
  107. // - When the crossorigin attribute of the link element of an external resource link that is already browsing-context connected is set, changed, or removed.
  108. name == AttributeNames::crossorigin
  109. // FIXME: - When the type attribute of the link element of an external resource link that is already browsing-context connected is set or changed to a value that does not or no longer matches the Content-Type metadata of the previous obtained external resource, if any.
  110. // FIXME: - When the type attribute of the link element of an external resource link that is already browsing-context connected, but was previously not obtained due to the type attribute specifying an unsupported type, is removed or changed.
  111. ) {
  112. fetch_and_process_linked_resource();
  113. }
  114. }
  115. }
  116. void HTMLLinkElement::resource_did_fail()
  117. {
  118. dbgln_if(CSS_LOADER_DEBUG, "HTMLLinkElement: Resource did fail. URL: {}", resource()->url());
  119. if (m_relationship & Relationship::Preload) {
  120. dispatch_event(*DOM::Event::create(realm(), HTML::EventNames::error).release_value_but_fixme_should_propagate_errors());
  121. }
  122. }
  123. void HTMLLinkElement::resource_did_load()
  124. {
  125. VERIFY(resource());
  126. if (m_relationship & Relationship::Icon) {
  127. resource_did_load_favicon();
  128. m_document_load_event_delayer.clear();
  129. }
  130. if (m_relationship & Relationship::Preload) {
  131. dispatch_event(*DOM::Event::create(realm(), HTML::EventNames::load).release_value_but_fixme_should_propagate_errors());
  132. }
  133. }
  134. void HTMLLinkElement::did_remove_attribute(DeprecatedFlyString const& attr)
  135. {
  136. if (m_relationship & Relationship::Stylesheet) {
  137. // https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:fetch-and-process-the-linked-resource
  138. // The appropriate times to fetch and process this type of link are:
  139. if (
  140. // - When the href attribute of the link element of an external resource link that is already browsing-context connected is changed.
  141. attr == AttributeNames::href ||
  142. // - When the disabled attribute of the link element of an external resource link that is already browsing-context connected is set, changed, or removed.
  143. attr == AttributeNames::disabled ||
  144. // - When the crossorigin attribute of the link element of an external resource link that is already browsing-context connected is set, changed, or removed.
  145. attr == AttributeNames::crossorigin
  146. // FIXME: - When the type attribute of the link element of an external resource link that is already browsing-context connected, but was previously not obtained due to the type attribute specifying an unsupported type, is removed or changed.
  147. ) {
  148. fetch_and_process_linked_resource();
  149. }
  150. }
  151. }
  152. // https://html.spec.whatwg.org/multipage/semantics.html#create-link-options-from-element
  153. HTMLLinkElement::LinkProcessingOptions HTMLLinkElement::create_link_options()
  154. {
  155. // 1. Let document be el's node document.
  156. auto& document = this->document();
  157. // 2. Let options be a new link processing options with
  158. LinkProcessingOptions options;
  159. // FIXME: destination the result of translating the state of el's as attribute
  160. // crossorigin the state of el's crossorigin content attribute
  161. options.crossorigin = cors_setting_attribute_from_keyword(
  162. has_attribute(AttributeNames::crossorigin) ? String::from_deprecated_string(get_attribute(AttributeNames::crossorigin)).release_value_but_fixme_should_propagate_errors()
  163. : Optional<String> {});
  164. // FIXME: referrer policy the state of el's referrerpolicy content attribute
  165. // FIXME: source set el's source set
  166. // base URL document's URL
  167. options.base_url = document.url();
  168. // origin document's origin
  169. options.origin = document.origin();
  170. // environment document's relevant settings object
  171. options.environment = &document.relevant_settings_object();
  172. // policy container document's policy container
  173. options.policy_container = document.policy_container();
  174. // document document
  175. options.document = &document;
  176. // FIXME: cryptographic nonce metadata The current value of el's [[CryptographicNonce]] internal slot
  177. // 3. If el has an href attribute, then set options's href to the value of el's href attribute.
  178. if (has_attribute(AttributeNames::href))
  179. options.href = String::from_deprecated_string(get_attribute(AttributeNames::href)).release_value_but_fixme_should_propagate_errors();
  180. // 4. If el has an integrity attribute, then set options's integrity to the value of el's integrity content attribute.
  181. if (has_attribute(AttributeNames::integrity))
  182. options.integrity = String::from_deprecated_string(get_attribute(AttributeNames::integrity)).release_value_but_fixme_should_propagate_errors();
  183. // 5. If el has a type attribute, then set options's type to the value of el's type attribute.
  184. if (has_attribute(AttributeNames::type))
  185. options.type = String::from_deprecated_string(get_attribute(AttributeNames::type)).release_value_but_fixme_should_propagate_errors();
  186. // FIXME: 6. Assert: options's href is not the empty string, or options's source set is not null.
  187. // A link element with neither an href or an imagesrcset does not represent a link.
  188. // 7. Return options.
  189. return options;
  190. }
  191. // https://html.spec.whatwg.org/multipage/semantics.html#create-a-link-request
  192. JS::GCPtr<Fetch::Infrastructure::Request> HTMLLinkElement::create_link_request(HTMLLinkElement::LinkProcessingOptions const& options)
  193. {
  194. // 1. Assert: options's href is not the empty string.
  195. // FIXME: 2. If options's destination is not a destination, then return null.
  196. // 3. Parse a URL given options's href, relative to options's base URL. If that fails, then return null. Otherwise, let url be the resulting URL record.
  197. auto url = options.base_url.complete_url(options.href);
  198. if (!url.is_valid())
  199. return nullptr;
  200. // 4. Let request be the result of creating a potential-CORS request given url, options's destination, and options's crossorigin.
  201. auto request = create_potential_CORS_request(vm(), url, options.destination, options.crossorigin);
  202. // 5. Set request's policy container to options's policy container.
  203. request->set_policy_container(options.policy_container);
  204. // 6. Set request's integrity metadata to options's integrity.
  205. request->set_integrity_metadata(options.integrity);
  206. // 7. Set request's cryptographic nonce metadata to options's cryptographic nonce metadata.
  207. request->set_cryptographic_nonce_metadata(options.cryptographic_nonce_metadata);
  208. // 8. Set request's referrer policy to options's referrer policy.
  209. request->set_referrer_policy(options.referrer_policy);
  210. // 9. Set request's client to options's environment.
  211. request->set_client(options.environment);
  212. // 10. Return request.
  213. return request;
  214. }
  215. // https://html.spec.whatwg.org/multipage/semantics.html#fetch-and-process-the-linked-resource
  216. void HTMLLinkElement::fetch_and_process_linked_resource()
  217. {
  218. default_fetch_and_process_linked_resource();
  219. }
  220. // https://html.spec.whatwg.org/multipage/semantics.html#default-fetch-and-process-the-linked-resource
  221. void HTMLLinkElement::default_fetch_and_process_linked_resource()
  222. {
  223. // https://html.spec.whatwg.org/multipage/semantics.html#the-link-element:attr-link-href-4
  224. // If both the href and imagesrcset attributes are absent, then the element does not define a link.
  225. // FIXME: Support imagesrcset attribute
  226. if (!has_attribute(AttributeNames::href) || href().is_empty())
  227. return;
  228. // 1. Let options be the result of creating link options from el.
  229. auto options = create_link_options();
  230. // 2. Let request be the result of creating a link request given options.
  231. auto request = create_link_request(options);
  232. // 3. If request is null, then return.
  233. if (request == nullptr) {
  234. return;
  235. }
  236. // FIXME: 4. Set request's synchronous flag.
  237. // 5. Run the linked resource fetch setup steps, given el and request. If the result is false, then return.
  238. if (!linked_resource_fetch_setup_steps(*request))
  239. return;
  240. // 6. Set request's initiator type to "css" if el's rel attribute contains the keyword stylesheet; "link" otherwise.
  241. if (m_relationship & Relationship::Stylesheet) {
  242. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::CSS);
  243. } else {
  244. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Link);
  245. }
  246. // 7. Fetch request with processResponseConsumeBody set to the following steps given response response and null, failure, or a byte sequence bodyBytes:
  247. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  248. fetch_algorithms_input.process_response_consume_body = [this, hr = options](auto response, auto body_bytes) {
  249. // FIXME: If the response is CORS cross-origin, we must use its internal response to query any of its data. See:
  250. // https://github.com/whatwg/html/issues/9355
  251. response = response->unsafe_response();
  252. // 1. Let success be true.
  253. bool success = true;
  254. // 2. If either of the following conditions are met:
  255. // - bodyBytes is null or failure; or
  256. // - response's status is not an ok status,
  257. if (body_bytes.template has<Empty>() || body_bytes.template has<Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag>() || !Fetch::Infrastructure::is_ok_status(response->status())) {
  258. // then set success to false.
  259. success = false;
  260. }
  261. // FIXME: 3. Otherwise, wait for the link resource's critical subresources to finish loading.
  262. // 4. Process the linked resource given el, success, response, and bodyBytes.
  263. process_linked_resource(success, response, body_bytes);
  264. };
  265. Fetch::Fetching::fetch(realm(), *request, Fetch::Infrastructure::FetchAlgorithms::create(vm(), move(fetch_algorithms_input))).release_value_but_fixme_should_propagate_errors();
  266. }
  267. // https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:process-the-linked-resource
  268. void HTMLLinkElement::process_stylesheet_resource(bool success, Fetch::Infrastructure::Response const& response, Variant<Empty, Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag, ByteBuffer> body_bytes)
  269. {
  270. // 1. If the resource's Content-Type metadata is not text/css, then set success to false.
  271. auto extracted_mime_type = response.header_list()->extract_mime_type().release_value_but_fixme_should_propagate_errors();
  272. if (!extracted_mime_type.has_value() || extracted_mime_type->essence() != "text/css") {
  273. success = false;
  274. }
  275. // FIXME: 2. If el no longer creates an external resource link that contributes to the styling processing model,
  276. // or if, since the resource in question was fetched, it has become appropriate to fetch it again, then return.
  277. // 3. If el has an associated CSS style sheet, remove the CSS style sheet.
  278. if (m_loaded_style_sheet) {
  279. document().style_sheets().remove_sheet(*m_loaded_style_sheet);
  280. m_loaded_style_sheet = nullptr;
  281. }
  282. // 4. If success is true, then:
  283. if (success) {
  284. // 1. Create a CSS style sheet with the following properties:
  285. // type
  286. // text/css
  287. // location
  288. // The resulting URL string determined during the fetch and process the linked resource algorithm.
  289. // owner node
  290. // element
  291. // media
  292. // The media attribute of element.
  293. // title
  294. // The title attribute of element, if element is in a document tree, or the empty string otherwise.
  295. // alternate flag
  296. // Set if the link is an alternative style sheet and element's explicitly enabled is false; unset otherwise.
  297. // origin-clean flag
  298. // Set if the resource is CORS-same-origin; unset otherwise.
  299. // parent CSS style sheet
  300. // owner CSS rule
  301. // null
  302. // disabled flag
  303. // Left at its default value.
  304. // CSS rules
  305. // Left uninitialized.
  306. //
  307. // The CSS environment encoding is the result of running the following steps: [CSSSYNTAX]
  308. // 1. If the element has a charset attribute, get an encoding from that attribute's value. If that succeeds, return the resulting encoding. [ENCODING]
  309. // 2. Otherwise, return the document's character encoding. [DOM]
  310. m_loaded_style_sheet = parse_css_stylesheet(CSS::Parser::ParsingContext(document(), *response.url()), body_bytes.template get<ByteBuffer>());
  311. if (m_loaded_style_sheet) {
  312. m_loaded_style_sheet->set_owner_node(this);
  313. document().style_sheets().add_sheet(*m_loaded_style_sheet);
  314. } else {
  315. dbgln_if(CSS_LOADER_DEBUG, "HTMLLinkElement: Failed to parse stylesheet: {}", resource()->url());
  316. }
  317. // 2. Fire an event named load at el.
  318. dispatch_event(*DOM::Event::create(realm(), HTML::EventNames::load).release_value_but_fixme_should_propagate_errors());
  319. }
  320. // 5. Otherwise, fire an event named error at el.
  321. else {
  322. dispatch_event(*DOM::Event::create(realm(), HTML::EventNames::error).release_value_but_fixme_should_propagate_errors());
  323. }
  324. // FIXME: 6. If el contributes a script-blocking style sheet, then:
  325. // FIXME: 1. Assert: el's node document's script-blocking style sheet counter is greater than 0.
  326. // FIXME: 2. Decrement el's node document's script-blocking style sheet counter by 1.
  327. // 7. Unblock rendering on el.
  328. m_document_load_event_delayer.clear();
  329. }
  330. // https://html.spec.whatwg.org/multipage/semantics.html#process-the-linked-resource
  331. void HTMLLinkElement::process_linked_resource(bool success, Fetch::Infrastructure::Response const& response, Variant<Empty, Fetch::Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag, ByteBuffer> body_bytes)
  332. {
  333. if (m_relationship & Relationship::Stylesheet)
  334. process_stylesheet_resource(success, response, body_bytes);
  335. }
  336. // https://html.spec.whatwg.org/multipage/semantics.html#linked-resource-fetch-setup-steps
  337. bool HTMLLinkElement::linked_resource_fetch_setup_steps(Fetch::Infrastructure::Request& request)
  338. {
  339. if (m_relationship & Relationship::Stylesheet)
  340. return stylesheet_linked_resource_fetch_setup_steps(request);
  341. return true;
  342. }
  343. // https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:linked-resource-fetch-setup-steps
  344. bool HTMLLinkElement::stylesheet_linked_resource_fetch_setup_steps(Fetch::Infrastructure::Request& request)
  345. {
  346. // 1. If el's disabled attribute is set, then return false.
  347. if (has_attribute(AttributeNames::disabled))
  348. return false;
  349. // FIXME: 2. If el contributes a script-blocking style sheet, increment el's node document's script-blocking style sheet counter by 1.
  350. // 3. If el's media attribute's value matches the environment and el is potentially render-blocking, then block rendering on el.
  351. // FIXME: Check media attribute value.
  352. m_document_load_event_delayer.emplace(document());
  353. // 4. If el is currently render-blocking, then set request's render-blocking to true.
  354. // FIXME: Check if el is currently render-blocking.
  355. request.set_render_blocking(true);
  356. // 5. Return true.
  357. return true;
  358. }
  359. void HTMLLinkElement::resource_did_load_favicon()
  360. {
  361. VERIFY(m_relationship & (Relationship::Icon));
  362. if (!resource()->has_encoded_data()) {
  363. dbgln_if(SPAM_DEBUG, "Favicon downloaded, no encoded data");
  364. return;
  365. }
  366. dbgln_if(SPAM_DEBUG, "Favicon downloaded, {} bytes from {}", resource()->encoded_data().size(), resource()->url());
  367. document().check_favicon_after_loading_link_resource();
  368. }
  369. bool HTMLLinkElement::load_favicon_and_use_if_window_is_active()
  370. {
  371. if (!has_loaded_icon())
  372. return false;
  373. RefPtr<Gfx::Bitmap> favicon_bitmap;
  374. auto decoded_image = Platform::ImageCodecPlugin::the().decode_image(resource()->encoded_data());
  375. if (!decoded_image.has_value() || decoded_image->frames.is_empty()) {
  376. dbgln("Could not decode favicon {}", resource()->url());
  377. return false;
  378. }
  379. favicon_bitmap = decoded_image->frames[0].bitmap;
  380. dbgln_if(IMAGE_DECODER_DEBUG, "Decoded favicon, {}", favicon_bitmap->size());
  381. auto* page = document().page();
  382. if (!page)
  383. return favicon_bitmap;
  384. if (document().browsing_context() == &page->top_level_browsing_context())
  385. if (favicon_bitmap) {
  386. page->client().page_did_change_favicon(*favicon_bitmap);
  387. return true;
  388. }
  389. return false;
  390. }
  391. void HTMLLinkElement::visit_edges(Cell::Visitor& visitor)
  392. {
  393. Base::visit_edges(visitor);
  394. visitor.visit(m_loaded_style_sheet);
  395. }
  396. }