HTMLLinkElement.cpp 23 KB

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