1use std::borrow::{Borrow, ToOwned};
6use std::cell::Cell;
7use std::default::Default;
8use std::str::FromStr;
9
10use bytes::BytesMut;
11use dom_struct::dom_struct;
12use html5ever::{LocalName, Prefix, local_name};
13use js::context::{JSContext, NoGC};
14use js::rust::HandleObject;
15use net_traits::image_cache::{
16 ImageCacheResponseCallback, ImageCacheResult, ImageLoadListener, ImageOrMetadataAvailable,
17 ImageResponse, PendingImageId,
18};
19use net_traits::request::{Destination, Initiator, ParserMetadata, RequestBuilder};
20use net_traits::{NetworkError, ReferrerPolicy};
21use script_bindings::cell::DomRefCell;
22use script_bindings::root::Dom;
23use servo_arc::Arc;
24use style::attr::AttrValue;
25use style::media_queries::MediaList as StyleMediaList;
26use style::stylesheets::Stylesheet;
27use stylo_atoms::Atom;
28
29use crate::css::stylesheet_loader::{
30 ElementStylesheetLoader, StylesheetContextSource, StylesheetOwner,
31};
32use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenList_Binding::DOMTokenListMethods;
33use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods;
34use crate::dom::bindings::inheritance::Castable;
35use crate::dom::bindings::refcounted::Trusted;
36use crate::dom::bindings::reflector::DomGlobal;
37use crate::dom::bindings::root::{DomRoot, MutNullableDom};
38use crate::dom::bindings::str::{DOMString, USVString};
39use crate::dom::css::cssstylesheet::CSSStyleSheet;
40use crate::dom::css::stylesheet::StyleSheet as DOMStyleSheet;
41use crate::dom::document::Document;
42use crate::dom::document::favicon::FaviconFetchContext;
43use crate::dom::documentorshadowroot::StylesheetSource;
44use crate::dom::domtokenlist::DOMTokenList;
45use crate::dom::element::attributes::storage::AttrRef;
46use crate::dom::element::{
47 AttributeMutation, Element, ElementCreator, cors_setting_for_element,
48 cors_settings_attribute_credential_mode, referrer_policy_for_element,
49 reflect_cross_origin_attribute, reflect_referrer_policy_attribute, set_cross_origin_attribute,
50};
51use crate::dom::html::document_metadata::processingoptions::{
52 LinkFetchContext, LinkFetchContextType, LinkProcessingOptions,
53};
54use crate::dom::html::htmlelement::HTMLElement;
55use crate::dom::html::links::relations::LinkRelations;
56use crate::dom::medialist::MediaList;
57use crate::dom::node::virtualmethods::VirtualMethods;
58use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext};
59use crate::dom::srcset::SourceSet;
60use crate::dom::types::EventTarget;
61use crate::scripting::fetching_options::ScriptFetchOptions;
62use crate::scripting::script_module::fetch_a_modulepreload_module;
63use crate::url::ensure_blob_referenced_by_url_is_kept_alive;
64
65#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
66pub(crate) struct RequestGenerationId(u32);
67
68impl RequestGenerationId {
69 fn increment(self) -> RequestGenerationId {
70 RequestGenerationId(self.0 + 1)
71 }
72}
73
74#[dom_struct]
75pub(crate) struct HTMLLinkElement {
76 htmlelement: HTMLElement,
77 rel_list: MutNullableDom<DOMTokenList>,
79
80 #[no_trace]
86 relations: Cell<LinkRelations>,
87
88 #[conditional_malloc_size_of]
89 #[no_trace]
90 stylesheet: DomRefCell<Option<Arc<Stylesheet>>>,
91 cssom_stylesheet: MutNullableDom<CSSStyleSheet>,
92
93 parser_inserted: Cell<bool>,
95 any_failed_load: Cell<bool>,
97 is_explicitly_enabled: Cell<bool>,
99 previous_type_matched: Cell<bool>,
101 pending_loads: Cell<u32>,
104 request_generation_id: Cell<RequestGenerationId>,
106
107 previous_media_environment_matched: Cell<bool>,
109 line_number: u64,
111 source_set: DomRefCell<SourceSet>,
113 blocking: MutNullableDom<DOMTokenList>,
115}
116
117impl HTMLLinkElement {
118 fn new_inherited(
119 local_name: LocalName,
120 prefix: Option<Prefix>,
121 document: &Document,
122 creator: ElementCreator,
123 ) -> HTMLLinkElement {
124 HTMLLinkElement {
125 htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
126 rel_list: Default::default(),
127 relations: Cell::new(LinkRelations::empty()),
128 parser_inserted: Cell::new(creator.is_parser_created()),
129 stylesheet: DomRefCell::new(None),
130 cssom_stylesheet: MutNullableDom::new(None),
131 pending_loads: Cell::new(0),
132 any_failed_load: Cell::new(false),
133 request_generation_id: Cell::new(RequestGenerationId(0)),
134 is_explicitly_enabled: Cell::new(false),
135 previous_type_matched: Cell::new(true),
136 previous_media_environment_matched: Cell::new(true),
137 line_number: creator.return_line_number(),
138 source_set: DomRefCell::new(SourceSet::new()),
139 blocking: Default::default(),
140 }
141 }
142
143 pub(crate) fn new(
144 cx: &mut js::context::JSContext,
145 local_name: LocalName,
146 prefix: Option<Prefix>,
147 document: &Document,
148 proto: Option<HandleObject>,
149 creator: ElementCreator,
150 ) -> DomRoot<HTMLLinkElement> {
151 Node::reflect_node_with_proto(
152 cx,
153 Box::new(HTMLLinkElement::new_inherited(
154 local_name, prefix, document, creator,
155 )),
156 document,
157 proto,
158 )
159 }
160
161 pub(crate) fn get_request_generation_id(&self) -> RequestGenerationId {
162 self.request_generation_id.get()
163 }
164
165 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
166 fn remove_stylesheet(&self, no_gc: &NoGC) {
167 if let Some(stylesheet) = self.stylesheet.safe_borrow_mut(no_gc).take() {
168 let owner = self.stylesheet_list_owner();
169 owner.remove_stylesheet(
170 StylesheetSource::Element(Dom::from_ref(self.upcast())),
171 &stylesheet,
172 );
173 self.clean_stylesheet_ownership();
174 owner.invalidate_stylesheets(no_gc);
175 }
176 }
177
178 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
181 pub(crate) fn set_stylesheet(&self, no_gc: &NoGC, new_stylesheet: Arc<Stylesheet>) {
182 let owner = self.stylesheet_list_owner();
183 if let Some(old_stylesheet) = self
184 .stylesheet
185 .safe_borrow_mut(no_gc)
186 .replace(new_stylesheet.clone())
187 {
188 owner.remove_stylesheet(
189 StylesheetSource::Element(Dom::from_ref(self.upcast())),
190 &old_stylesheet,
191 );
192 }
193 owner.add_owned_stylesheet(no_gc, self.upcast(), new_stylesheet);
194 }
195
196 pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
197 self.stylesheet.borrow().clone()
198 }
199
200 pub(crate) fn get_cssom_stylesheet(
201 &self,
202 cx: &mut JSContext,
203 ) -> Option<DomRoot<CSSStyleSheet>> {
204 self.get_stylesheet().map(|sheet| {
205 self.cssom_stylesheet.or_init(|| {
206 CSSStyleSheet::new(
207 cx,
208 &self.owner_window(),
209 Some(self.upcast::<Element>()),
210 DOMString::from_static("text/css"),
211 Some(self.Href().into()),
212 sheet,
213 None, )
215 })
216 })
217 }
218
219 pub(crate) fn is_alternate(&self) -> bool {
220 self.relations.get().contains(LinkRelations::ALTERNATE) &&
221 !self
222 .upcast::<Element>()
223 .get_string_attribute(&local_name!("title"))
224 .is_empty()
225 }
226
227 pub(crate) fn is_effectively_disabled(&self) -> bool {
228 (self.is_alternate() && !self.is_explicitly_enabled.get()) ||
229 self.upcast::<Element>()
230 .has_attribute(&local_name!("disabled"))
231 }
232
233 fn clean_stylesheet_ownership(&self) {
234 if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
235 cssom_stylesheet.set_owner_node(None);
236 }
237 self.cssom_stylesheet.set(None);
238 }
239}
240
241impl VirtualMethods for HTMLLinkElement {
242 fn super_type(&self) -> Option<&dyn VirtualMethods> {
243 Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
244 }
245
246 fn attribute_mutated(
247 &self,
248 cx: &mut js::context::JSContext,
249 attr: AttrRef<'_>,
250 mutation: AttributeMutation,
251 ) {
252 self.super_type()
253 .unwrap()
254 .attribute_mutated(cx, attr, mutation);
255
256 let local_name = attr.local_name();
257 let is_removal = mutation.is_removal();
258 match *local_name {
259 local_name!("disabled") => {
260 self.handle_disabled_attribute_change(cx.no_gc(), is_removal);
261 return;
262 },
263 local_name!("rel") | local_name!("rev") => {
264 let previous_relations = self.relations.get();
265 self.relations
266 .set(LinkRelations::for_element(self.upcast()));
267
268 if previous_relations == self.relations.get() {
270 return;
271 }
272 },
273 _ => {},
274 }
275
276 let node = self.upcast::<Node>();
277 if !node.is_connected() {
278 return;
279 }
280
281 if self.relations.get().contains(LinkRelations::STYLESHEET) &&
284 let AttributeMutation::Set(Some(previous_value)) = mutation &&
285 **previous_value == **attr.value()
286 {
287 return;
288 }
289
290 match *local_name {
291 local_name!("rel") | local_name!("rev") => {
292 if self.relations.get().contains(LinkRelations::STYLESHEET) {
295 self.handle_stylesheet_url(cx);
296 } else {
297 self.remove_stylesheet(cx.no_gc());
298 }
299
300 if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
301 self.fetch_and_process_modulepreload(cx);
302 }
303
304 if self.relations.get().contains(LinkRelations::ICON) {
305 self.owner_document().set_ever_had_favicon_link(true);
306 }
307 },
308 local_name!("href") => {
309 if is_removal {
312 if self.relations.get().contains(LinkRelations::STYLESHEET) {
313 self.remove_stylesheet(cx.no_gc());
314 }
315 return;
316 }
317 if self.relations.get().contains(LinkRelations::STYLESHEET) {
321 self.handle_stylesheet_url(cx);
322 }
323
324 if self.relations.get().contains(LinkRelations::ICON) {
325 self.handle_favicon_url(&attr.value());
326 }
327
328 if self.relations.get().contains(LinkRelations::PREFETCH) {
332 self.fetch_and_process_prefetch_link(&attr.value());
333 }
334
335 if self.relations.get().contains(LinkRelations::PRELOAD) {
339 self.handle_preload_url(cx.no_gc());
340 }
341
342 if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
344 self.fetch_and_process_modulepreload(cx);
345 }
346 },
347 local_name!("imagesrcset") => {
348 self.source_set
349 .safe_borrow_mut(cx.no_gc())
350 .update_source_set(cx.no_gc(), self.upcast::<Element>());
351 },
352 local_name!("imagesizes") => {
353 if self
354 .upcast::<Element>()
355 .has_attribute(&local_name!("imagesrcset"))
356 {
357 self.source_set
358 .safe_borrow_mut(cx.no_gc())
359 .update_source_set(cx.no_gc(), self.upcast::<Element>());
360 }
361 },
362 local_name!("sizes") if self.relations.get().contains(LinkRelations::ICON) => {
363 self.handle_favicon_url(&attr.value());
364 },
365 local_name!("crossorigin") => {
366 if self.relations.get().contains(LinkRelations::PREFETCH) {
370 self.fetch_and_process_prefetch_link(&attr.value());
371 }
372
373 if self.relations.get().contains(LinkRelations::STYLESHEET) {
377 self.handle_stylesheet_url(cx);
378 }
379 },
380 local_name!("as") => {
381 if self.relations.get().contains(LinkRelations::PRELOAD) &&
385 let AttributeMutation::Set(Some(_)) = mutation
386 {
387 self.handle_preload_url(cx.no_gc());
388 }
389 },
390 local_name!("type") => {
391 if self.relations.get().contains(LinkRelations::STYLESHEET) {
399 self.handle_stylesheet_url(cx);
400 }
401
402 if self.relations.get().contains(LinkRelations::PRELOAD) &&
408 !self.previous_type_matched.get()
409 {
410 self.handle_preload_url(cx.no_gc());
411 }
412 },
413 local_name!("media") => {
414 if self.relations.get().contains(LinkRelations::PRELOAD) &&
419 !self.previous_media_environment_matched.get()
420 {
421 match mutation {
422 AttributeMutation::Removed | AttributeMutation::Set(Some(_)) => {
423 self.handle_preload_url(cx.no_gc())
424 },
425 _ => {},
426 };
427 } else if self.relations.get().contains(LinkRelations::STYLESHEET) &&
428 let Some(ref stylesheet) = *self.stylesheet.safe_borrow_mut(cx.no_gc())
429 {
430 let document = self.owner_document();
431 let shared_lock = document.style_shared_author_lock().clone();
432 let mut guard = shared_lock.write();
433 let media = stylesheet.media.write_with(&mut guard);
434 match mutation {
435 AttributeMutation::Set(_) => {
436 *media = MediaList::parse_media_list(&attr.value(), document.window())
437 },
438 AttributeMutation::Removed => *media = StyleMediaList::empty(),
439 };
440 self.owner_document().invalidate_stylesheets(cx.no_gc());
441 }
442
443 let matches_media_environment =
444 MediaList::matches_environment(&self.owner_document(), &attr.value());
445 self.previous_media_environment_matched
446 .set(matches_media_environment);
447 },
448 _ => {},
449 }
450 }
451
452 fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
453 match name {
454 &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
455 _ => self
456 .super_type()
457 .unwrap()
458 .parse_plain_attribute(name, value),
459 }
460 }
461
462 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
463 if let Some(s) = self.super_type() {
464 s.bind_to_tree(cx, context);
465 }
466
467 let element = self.upcast::<Element>();
468 let href = element.get_attribute_string_value(&local_name!("href"));
469
470 if context.tree_connected && self.relations.get().contains(LinkRelations::ICON) {
471 self.owner_document().set_ever_had_favicon_link(true);
472 }
473
474 if context.tree_connected &&
475 (href.as_ref().is_some_and(|x| !x.is_empty()) ||
476 element.has_attribute(&local_name!("imagesrcset")))
477 {
478 let relations = self.relations.get();
479 if let Some(href) = href {
482 if relations.contains(LinkRelations::STYLESHEET) {
483 self.handle_stylesheet_url(cx);
484 }
485
486 if relations.contains(LinkRelations::ICON) {
487 self.handle_favicon_url(&href);
488 }
489
490 if relations.contains(LinkRelations::PREFETCH) {
491 self.fetch_and_process_prefetch_link(&href);
492 }
493
494 if relations.contains(LinkRelations::MODULE_PRELOAD) {
496 let link = DomRoot::from_ref(self);
497 self.owner_document().add_delayed_task(
498 task!(FetchModulePreload: |cx, link: DomRoot<HTMLLinkElement>| {
499 link.fetch_and_process_modulepreload(cx);
500 }),
501 );
502 }
503 }
504
505 if relations.contains(LinkRelations::PRELOAD) {
506 self.handle_preload_url(cx.no_gc());
507 }
508 }
509 }
510
511 fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
512 if let Some(s) = self.super_type() {
513 s.unbind_from_tree(cx, context);
514 }
515
516 self.remove_stylesheet(cx.no_gc());
517 }
518}
519
520impl HTMLLinkElement {
521 fn compute_destination_for_attribute(&self) -> Option<Destination> {
522 let element = self.upcast::<Element>();
525 element
526 .get_attribute_string_ref(&local_name!("as"))
527 .and_then(|attr| {
528 let attr = attr.as_attr_ref().value();
529 LinkProcessingOptions::translate_a_preload_destination(&attr)
530 })
531 }
532
533 fn processing_options(&self) -> LinkProcessingOptions {
535 let element = self.upcast::<Element>();
536
537 let document = self.upcast::<Node>().owner_doc();
539 let global = document.owner_global();
540
541 let mut options = LinkProcessingOptions {
543 href: String::new(),
544 destination: Destination::None,
545 integrity: String::new(),
546 link_type: String::new(),
547 cryptographic_nonce_metadata: self.upcast::<Element>().nonce_value(),
548 cross_origin: cors_setting_for_element(element),
549 referrer_policy: referrer_policy_for_element(element),
550 policy_container: document.policy_container().clone(),
551 source_set: Some(self.source_set.borrow().clone()),
552 origin: document.borrow().origin().immutable().to_owned(),
553 request_client: global.request_client(None),
554 referrer: global.get_referrer(),
555 fetch_priority: element
556 .get_attribute_string_ref(&local_name!("fetchpriority"))
557 .unwrap_or_default()
558 .value()
559 .as_ref()
560 .into(),
561 };
562
563 if let Some(href_attribute) = element.get_attribute_string_value(&local_name!("href")) {
565 options.href = href_attribute;
566 }
567
568 if let Some(integrity_attribute) =
571 element.get_attribute_string_value(&local_name!("integrity"))
572 {
573 options.integrity = integrity_attribute;
574 }
575
576 if let Some(type_attribute) = element.get_attribute_string_value(&local_name!("type")) {
578 options.link_type = type_attribute;
579 }
580
581 assert!(!options.href.is_empty() || options.source_set.is_some());
583
584 options
586 }
587
588 fn default_fetch_and_process_the_linked_resource(&self) -> Option<RequestBuilder> {
593 let options = self.processing_options();
595
596 let document = self.upcast::<Node>().owner_doc();
598 let Some(request) = options.create_link_request(
599 self.owner_window().webview_id(),
600 &self.owner_global(),
601 &document,
602 ) else {
603 return None;
605 };
606 let mut request = request.synchronous(true);
608
609 if !self.linked_resource_fetch_setup(&mut request) {
611 return None;
612 }
613
614 Some(request)
620 }
621
622 fn linked_resource_fetch_setup(&self, request: &mut RequestBuilder) -> bool {
624 if self.relations.get().contains(LinkRelations::ICON) {
626 request.destination = Destination::Image;
628
629 }
633
634 if self.relations.get().contains(LinkRelations::STYLESHEET) {
636 if self
638 .upcast::<Element>()
639 .has_attribute(&local_name!("disabled"))
640 {
641 return false;
642 }
643 }
658
659 true
660 }
661
662 fn fetch_and_process_prefetch_link(&self, href: &str) {
664 if href.is_empty() {
666 return;
667 }
668
669 let mut options = self.processing_options();
671
672 options.destination = Destination::None;
674
675 let document = self.upcast::<Node>().owner_doc();
677 let Some(request) = options.create_link_request(
678 self.owner_window().webview_id(),
679 &self.owner_global(),
680 &document,
681 ) else {
682 return;
684 };
685 let url = request.url.url();
686
687 let request = request.initiator(Initiator::Prefetch);
689
690 let fetch_context = LinkFetchContext {
694 url,
695 link: Some(Trusted::new(self)),
696 type_: LinkFetchContextType::Prefetch,
697 response_body: BytesMut::new(),
698 };
699
700 document.fetch_background(request, fetch_context);
701 }
702
703 fn handle_stylesheet_url(&self, cx: &mut js::context::JSContext) {
705 let document = self.owner_document();
706 if document.browsing_context().is_none() {
707 return;
708 }
709
710 let element = self.upcast::<Element>();
711
712 let type_ = element.get_string_attribute(&local_name!("type"));
719 if !type_.is_empty() && !type_.eq_ignore_ascii_case("text/css") {
720 return;
721 }
722
723 let href = element.get_string_attribute(&local_name!("href"));
725 if href.is_empty() {
726 return;
727 }
728
729 let link_url = match document.encoding_parse_a_url(&href.str()) {
731 Ok(url) => url,
732 Err(e) => {
733 debug!("Parsing url {} failed: {}", href, e);
734 return;
735 },
736 };
737
738 let cors_setting = cors_setting_for_element(element);
740
741 let media_query_string = element
742 .get_attribute_string_ref(&local_name!("media"))
743 .unwrap_or_default();
744 let media = MediaList::parse_media_list(
745 &media_query_string.as_attr_ref().value(),
746 document.window(),
747 );
748 let media = Arc::new(document.style_shared_author_lock().wrap(media));
749
750 let integrity_metadata = element
751 .get_attribute_string_value(&local_name!("integrity"))
752 .unwrap_or_default();
753
754 self.request_generation_id
755 .set(self.request_generation_id.get().increment());
756 self.pending_loads.set(0);
757
758 ElementStylesheetLoader::load_with_element(
759 cx,
760 self.upcast(),
761 StylesheetContextSource::LinkElement,
762 media,
763 link_url,
764 cors_setting,
765 integrity_metadata,
766 );
767 }
768
769 fn handle_disabled_attribute_change(&self, no_gc: &NoGC, is_removal: bool) {
771 if is_removal {
773 self.is_explicitly_enabled.set(true);
774 }
775 if let Some(stylesheet) = self.get_stylesheet() &&
776 stylesheet.set_disabled(!is_removal)
777 {
778 self.stylesheet_list_owner().invalidate_stylesheets(no_gc);
779 }
780 }
781
782 fn handle_favicon_url(&self, href: &str) {
783 if href.is_empty() {
785 return;
786 }
787
788 let window = self.owner_window();
791 if !window.is_top_level() {
792 return;
793 }
794
795 let document = self.upcast::<Node>().owner_doc();
797 let Ok(favicon_url) = document.encoding_parse_a_url(&self.Href()) else {
798 return;
799 };
800
801 self.request_generation_id
803 .set(self.request_generation_id.get().increment());
804
805 let cache_result = window.image_cache().get_cached_image_status(
806 favicon_url.clone(),
807 window.origin().immutable(),
808 cors_setting_for_element(self.upcast()),
809 );
810
811 match cache_result {
812 ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
813 image, ..
814 }) => {
815 self.owner_document().process_favicon_image(image, false);
816 },
817 ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
818 ImageCacheResult::Pending(id) => {
819 let sender = self.register_image_cache_callback(id);
820 window.image_cache().add_listener(ImageLoadListener::new(
821 sender,
822 window.pipeline_id(),
823 id,
824 ));
825 },
826 ImageCacheResult::ReadyForRequest(id) => {
827 let Some(request) = self.default_fetch_and_process_the_linked_resource() else {
828 return;
829 };
830
831 let sender = self.register_image_cache_callback(id);
832 window.image_cache().add_listener(ImageLoadListener::new(
833 sender,
834 window.pipeline_id(),
835 id,
836 ));
837
838 let fetch_context =
839 FaviconFetchContext::new(window.image_cache(), id, favicon_url, false);
840 document.fetch_favicon(request, fetch_context);
841 },
842 ImageCacheResult::FailedToLoadOrDecode => {},
843 };
844 }
845
846 fn register_image_cache_callback(&self, id: PendingImageId) -> ImageCacheResponseCallback {
847 let trusted_node = Trusted::new(self);
848 let window = self.owner_window();
849 let request_generation_id = self.get_request_generation_id();
850 window.register_image_cache_listener(id, move |response, _| {
851 let trusted_node = trusted_node.clone();
852 let link_element = trusted_node.root();
853 let window = link_element.owner_window();
854
855 let ImageResponse::Loaded(image, _) = response.response else {
856 return;
858 };
859
860 if request_generation_id != link_element.get_request_generation_id() {
861 return;
863 };
864
865 window
866 .as_global_scope()
867 .task_manager()
868 .networking_task_source()
869 .queue(task!(process_favicon_response: move || {
870 let element = trusted_node.root();
871
872 if request_generation_id != element.get_request_generation_id() {
873 return;
875 };
876
877 element.owner_document().process_favicon_image(image, false);
878 }));
879 })
880 }
881
882 fn handle_preload_url(&self, no_gc: &NoGC) {
885 self.source_set
887 .safe_borrow_mut(no_gc)
888 .update_source_set(no_gc, self.upcast::<Element>());
889 let mut options = self.processing_options();
891 let Some(destination) = self.compute_destination_for_attribute() else {
894 return;
896 };
897 options.destination = destination;
899 {
901 let type_matches_destination = options.type_matches_destination();
903 self.previous_type_matched.set(type_matches_destination);
904 if !type_matches_destination {
905 return;
906 }
907 }
908 let document = self.upcast::<Node>().owner_doc();
910 options.preload(
911 self.owner_window_unrooted(no_gc).webview_id(),
912 Some(Trusted::new(self)),
913 &document,
914 );
915 }
916
917 pub(crate) fn fire_event_after_response(
919 &self,
920 cx: &mut JSContext,
921 response: Result<(), NetworkError>,
922 ) {
923 if response.is_err() {
926 self.upcast::<EventTarget>().fire_event(cx, atom!("error"));
927 } else {
928 self.upcast::<EventTarget>().fire_event(cx, atom!("load"));
929 }
930 }
931
932 fn fetch_and_process_modulepreload(&self, cx: &mut JSContext) {
934 let el = self.upcast::<Element>();
935 let href_attribute_value = el.get_string_attribute(&local_name!("href"));
936
937 if href_attribute_value.is_empty() {
939 return;
940 }
941
942 let destination = el
944 .get_attribute_string_value(&local_name!("as"))
945 .map(|mut value| {
946 value.make_ascii_lowercase();
947 value
948 })
949 .and_then(|value| match value.as_str() {
950 "" => None,
952 "fetch" => Some(Destination::None),
954 _ => Destination::from_str(&value).ok(),
955 })
956 .unwrap_or(Destination::Script);
957
958 let document = self.owner_document_unrooted(cx.no_gc());
959 let global = document.global();
960
961 let is_a_modulepreload_destination = match destination {
963 Destination::Json | Destination::Style | Destination::Text => true,
964 Destination::Xslt => false,
967 d => d.is_script_like(),
968 };
969
970 if !is_a_modulepreload_destination {
973 return global
974 .task_manager()
975 .networking_task_source()
976 .queue_simple_event(self.upcast(), atom!("error"));
977 }
978
979 let Ok(url) = document.encoding_parse_a_url(&href_attribute_value.str()) else {
982 return;
983 };
984 let url = ensure_blob_referenced_by_url_is_kept_alive(&global, url);
985
986 let credentials_mode = cors_settings_attribute_credential_mode(el);
990
991 let cryptographic_nonce = el.nonce_value();
993
994 let integrity_metadata = el
998 .get_attribute_string_value(&local_name!("integrity"))
999 .unwrap_or_else(|| {
1000 global
1001 .import_map()
1002 .resolve_a_module_integrity_metadata(&url.url())
1003 });
1004
1005 let referrer_policy = referrer_policy_for_element(el);
1007
1008 let fetch_priority = self.FetchPriority().into();
1010
1011 let options = ScriptFetchOptions {
1015 cryptographic_nonce,
1016 integrity_metadata,
1017 parser_metadata: ParserMetadata::NotParserInserted,
1018 credentials_mode,
1019 referrer_policy,
1020 render_blocking: false,
1021 fetch_priority,
1022 };
1023
1024 let link = DomRoot::from_ref(self);
1025
1026 fetch_a_modulepreload_module(
1029 cx,
1030 url,
1031 destination,
1032 &global,
1033 options,
1034 move |cx, fetch_failed| {
1035 let event = match fetch_failed {
1038 true => atom!("error"),
1039 false => atom!("load"),
1040 };
1041
1042 link.upcast::<EventTarget>().fire_event(cx, event);
1043 },
1044 );
1045 }
1046}
1047
1048impl StylesheetOwner for HTMLLinkElement {
1049 fn increment_pending_loads_count(&self) {
1050 self.pending_loads.set(self.pending_loads.get() + 1)
1051 }
1052
1053 fn load_finished(&self, succeeded: bool) -> Option<bool> {
1054 assert!(self.pending_loads.get() > 0, "What finished?");
1055 if !succeeded {
1056 self.any_failed_load.set(true);
1057 }
1058
1059 self.pending_loads.set(self.pending_loads.get() - 1);
1060 if self.pending_loads.get() != 0 {
1061 return None;
1062 }
1063
1064 let any_failed = self.any_failed_load.get();
1065 self.any_failed_load.set(false);
1066 Some(any_failed)
1067 }
1068
1069 fn parser_inserted(&self) -> bool {
1070 self.parser_inserted.get()
1071 }
1072
1073 fn potentially_render_blocking(&self) -> bool {
1075 self.parser_inserted() ||
1082 self.blocking
1083 .get()
1084 .is_some_and(|list| list.Contains(DOMString::from_static("render")))
1085 }
1086
1087 fn referrer_policy(&self, cx: &mut js::context::JSContext) -> ReferrerPolicy {
1088 if self
1089 .RelList(cx)
1090 .Contains(DOMString::from_static("noreferrer"))
1091 {
1092 return ReferrerPolicy::NoReferrer;
1093 }
1094
1095 ReferrerPolicy::EmptyString
1096 }
1097
1098 fn set_origin_clean(&self, cx: &mut js::context::JSContext, origin_clean: bool) {
1099 if let Some(stylesheet) = self.get_cssom_stylesheet(cx) {
1100 stylesheet.set_origin_clean(origin_clean);
1101 }
1102 }
1103}
1104
1105impl HTMLLinkElementMethods<crate::DomTypeHolder> for HTMLLinkElement {
1106 make_url_getter!(Href, "href");
1108
1109 make_url_setter!(SetHref, "href");
1111
1112 make_getter!(Rel, "rel");
1114
1115 fn SetRel(&self, cx: &mut JSContext, rel: DOMString) {
1117 self.upcast::<Element>()
1118 .set_tokenlist_attribute(cx, &local_name!("rel"), rel);
1119 }
1120
1121 make_enumerated_getter!(
1123 As,
1124 "as",
1125 "fetch" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame"
1126 | "iframe" | "image" | "json" | "manifest" | "object" | "paintworklet"
1127 | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track"
1128 | "video" | "webidentity" | "worker" | "xslt",
1129 missing => "",
1130 invalid => ""
1131 );
1132
1133 make_setter!(SetAs, "as");
1135
1136 make_getter!(Media, "media");
1138
1139 make_setter!(SetMedia, "media");
1141
1142 make_getter!(Integrity, "integrity");
1144
1145 make_setter!(SetIntegrity, "integrity");
1147
1148 make_getter!(Hreflang, "hreflang");
1150
1151 make_setter!(SetHreflang, "hreflang");
1153
1154 make_getter!(Type, "type");
1156
1157 make_setter!(SetType, "type");
1159
1160 make_url_getter!(ImageSrcset, "imagesrcset");
1162
1163 make_url_setter!(SetImageSrcset, "imagesrcset");
1165
1166 make_getter!(ImageSizes, "imagesizes");
1168
1169 make_setter!(SetImageSizes, "imagesizes");
1171
1172 make_bool_getter!(Disabled, "disabled");
1174
1175 make_bool_setter!(SetDisabled, "disabled");
1177
1178 fn RelList(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1180 self.rel_list.or_init(|| {
1181 DOMTokenList::new(
1182 cx,
1183 self.upcast(),
1184 &local_name!("rel"),
1185 Some(vec![
1186 Atom::from("alternate"),
1187 Atom::from("apple-touch-icon"),
1188 Atom::from("apple-touch-icon-precomposed"),
1189 Atom::from("canonical"),
1190 Atom::from("dns-prefetch"),
1191 Atom::from("icon"),
1192 Atom::from("import"),
1193 Atom::from("manifest"),
1194 Atom::from("modulepreload"),
1195 Atom::from("next"),
1196 Atom::from("preconnect"),
1197 Atom::from("prefetch"),
1198 Atom::from("preload"),
1199 Atom::from("prerender"),
1200 Atom::from("stylesheet"),
1201 ]),
1202 )
1203 })
1204 }
1205
1206 make_getter!(Charset, "charset");
1208
1209 make_setter!(SetCharset, "charset");
1211
1212 make_getter!(Rev, "rev");
1214
1215 make_setter!(SetRev, "rev");
1217
1218 make_getter!(Target, "target");
1220
1221 make_setter!(SetTarget, "target");
1223
1224 fn Blocking(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1226 self.blocking.or_init(|| {
1227 DOMTokenList::new(
1228 cx,
1229 self.upcast(),
1230 &local_name!("blocking"),
1231 Some(vec![Atom::from("render")]),
1232 )
1233 })
1234 }
1235
1236 fn GetCrossOrigin(&self) -> Option<DOMString> {
1238 reflect_cross_origin_attribute(self.upcast::<Element>())
1239 }
1240
1241 fn SetCrossOrigin(&self, cx: &mut JSContext, value: Option<DOMString>) {
1243 set_cross_origin_attribute(cx, self.upcast::<Element>(), value);
1244 }
1245
1246 fn ReferrerPolicy(&self) -> DOMString {
1248 reflect_referrer_policy_attribute(self.upcast::<Element>())
1249 }
1250
1251 make_setter!(SetReferrerPolicy, "referrerpolicy");
1253
1254 fn GetSheet(&self, cx: &mut JSContext) -> Option<DomRoot<DOMStyleSheet>> {
1256 self.get_cssom_stylesheet(cx).map(DomRoot::upcast)
1257 }
1258
1259 make_enumerated_getter!(
1261 FetchPriority,
1262 "fetchpriority",
1263 "high" | "low" | "auto",
1264 missing => "auto",
1265 invalid => "auto"
1266 );
1267 make_setter!(SetFetchPriority, "fetchpriority");
1269}