HTMLLinkElement.cpp 22 KB

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