Skip to main content

script/dom/html/document_metadata/
htmllinkelement.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use 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    /// The relations as specified by the "rel" attribute
78    rel_list: MutNullableDom<DOMTokenList>,
79
80    /// The link relations as they are used in practice.
81    ///
82    /// The reason this is separate from [HTMLLinkElement::rel_list] is that
83    /// a literal list is a bit unwieldy and that there are corner cases to consider
84    /// (Like `rev="made"` implying an author relationship that is not represented in rel_list)
85    #[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    /// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts>
94    parser_inserted: Cell<bool>,
95    /// Whether any of the loads have failed.
96    any_failed_load: Cell<bool>,
97    /// <https://html.spec.whatwg.org/multipage/#explicitly-enabled>
98    is_explicitly_enabled: Cell<bool>,
99    /// Whether the previous type matched with the destination
100    previous_type_matched: Cell<bool>,
101    /// The number of loads that this link element has triggered (could be more
102    /// than one because of imports) and have not yet finished.
103    pending_loads: Cell<u32>,
104    /// A monotonically increasing counter that keeps track of which stylesheet to apply.
105    request_generation_id: Cell<RequestGenerationId>,
106
107    /// Whether the previous media environment matched with the media query
108    previous_media_environment_matched: Cell<bool>,
109    /// Line number this element was created on
110    line_number: u64,
111    /// <https://html.spec.whatwg.org/multipage/#source-set>
112    source_set: DomRefCell<SourceSet>,
113    /// <https://html.spec.whatwg.org/multipage/#dom-link-blocking>
114    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    // FIXME(emilio): These methods are duplicated with
179    // HTMLStyleElement::set_stylesheet.
180    #[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, // constructor_document
214                )
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 relations haven't changed, we shouldn't do anything
269                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        // For stylesheets, we should only refetch when the actual attribute value
282        // has been changed.
283        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                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
293                // > When the external resource link is created on a link element that is already browsing-context connected.
294                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                // https://html.spec.whatwg.org/multipage/#attr-link-href
310                // > If both the href and imagesrcset attributes are absent, then the element does not define a link.
311                if is_removal {
312                    if self.relations.get().contains(LinkRelations::STYLESHEET) {
313                        self.remove_stylesheet(cx.no_gc());
314                    }
315                    return;
316                }
317                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
318                // > When the href attribute of the link element of an external resource link
319                // > that is already browsing-context connected is changed.
320                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                // https://html.spec.whatwg.org/multipage/#link-type-prefetch
329                // When the href attribute of the link element of an external resource link
330                // that is already browsing-context connected is changed.
331                if self.relations.get().contains(LinkRelations::PREFETCH) {
332                    self.fetch_and_process_prefetch_link(&attr.value());
333                }
334
335                // https://html.spec.whatwg.org/multipage/#link-type-preload
336                // When the href attribute of the link element of an external resource link
337                // that is already browsing-context connected is changed.
338                if self.relations.get().contains(LinkRelations::PRELOAD) {
339                    self.handle_preload_url(cx.no_gc());
340                }
341
342                // https://html.spec.whatwg.org/multipage/#link-type-modulepreload
343                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                // https://html.spec.whatwg.org/multipage/#link-type-prefetch
367                // When the crossorigin attribute of the link element of an external resource link
368                // that is already browsing-context connected is set, changed, or removed.
369                if self.relations.get().contains(LinkRelations::PREFETCH) {
370                    self.fetch_and_process_prefetch_link(&attr.value());
371                }
372
373                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet
374                // When the crossorigin attribute of the link element of an external resource link
375                // that is already browsing-context connected is set, changed, or removed.
376                if self.relations.get().contains(LinkRelations::STYLESHEET) {
377                    self.handle_stylesheet_url(cx);
378                }
379            },
380            local_name!("as") => {
381                // https://html.spec.whatwg.org/multipage/#link-type-preload
382                // When the as attribute of the link element of an external resource link
383                // that is already browsing-context connected is changed.
384                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                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
392                // When the type attribute of the link element of an external resource link that
393                // is already browsing-context connected is set or changed to a value that does
394                // not or no longer matches the Content-Type metadata of the previous obtained
395                // external resource, if any.
396                //
397                // TODO: Match Content-Type metadata to check if it needs to be updated
398                if self.relations.get().contains(LinkRelations::STYLESHEET) {
399                    self.handle_stylesheet_url(cx);
400                }
401
402                // https://html.spec.whatwg.org/multipage/#link-type-preload
403                // When the type attribute of the link element of an external resource link that
404                // is already browsing-context connected, but was previously not obtained due to
405                // the type attribute specifying an unsupported type for the request destination,
406                // is set, removed, or changed.
407                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                // https://html.spec.whatwg.org/multipage/#link-type-preload
415                // When the media attribute of the link element of an external resource link that
416                // is already browsing-context connected, but was previously not obtained due to
417                // the media attribute not matching the environment, is changed or removed.
418                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            // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
480            // > When the external resource link's link element becomes browsing-context connected.
481            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                // https://html.spec.whatwg.org/multipage/#link-type-modulepreload
495                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 destination be the result of translating the keyword
523        // representing the state of el's as attribute.
524        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    /// <https://html.spec.whatwg.org/multipage/#create-link-options-from-element>
534    fn processing_options(&self) -> LinkProcessingOptions {
535        let element = self.upcast::<Element>();
536
537        // Step 1. Let document be el's node document.
538        let document = self.upcast::<Node>().owner_doc();
539        let global = document.owner_global();
540
541        // Step 2. Let options be a new link processing options
542        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        // Step 3. If el has an href attribute, then set options's href to the value of el's href attribute.
564        if let Some(href_attribute) = element.get_attribute_string_value(&local_name!("href")) {
565            options.href = href_attribute;
566        }
567
568        // Step 4. If el has an integrity attribute, then set options's integrity
569        //         to the value of el's integrity content attribute.
570        if let Some(integrity_attribute) =
571            element.get_attribute_string_value(&local_name!("integrity"))
572        {
573            options.integrity = integrity_attribute;
574        }
575
576        // Step 5. If el has a type attribute, then set options's type to the value of el's type attribute.
577        if let Some(type_attribute) = element.get_attribute_string_value(&local_name!("type")) {
578            options.link_type = type_attribute;
579        }
580
581        // Step 6. Assert: options's href is not the empty string, or options's source set is not null.
582        assert!(!options.href.is_empty() || options.source_set.is_some());
583
584        // Step 7. Return options.
585        options
586    }
587
588    /// <https://html.spec.whatwg.org/multipage/#default-fetch-and-process-the-linked-resource>
589    ///
590    /// This method does not implement Step 7 (fetching the request) and instead returns the [RequestBuilder],
591    /// as the fetch context that should be used depends on the link type.
592    fn default_fetch_and_process_the_linked_resource(&self) -> Option<RequestBuilder> {
593        // Step 1. Let options be the result of creating link options from el.
594        let options = self.processing_options();
595
596        // Step 2. Let request be the result of creating a link request given options.
597        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            // Step 3. If request is null, then return.
604            return None;
605        };
606        // Step 4. Set request's synchronous flag.
607        let mut request = request.synchronous(true);
608
609        // Step 5. Run the linked resource fetch setup steps, given el and request. If the result is false, then return.
610        if !self.linked_resource_fetch_setup(&mut request) {
611            return None;
612        }
613
614        // TODO Step 6. Set request's initiator type to "css" if el's rel attribute
615        // contains the keyword stylesheet; "link" otherwise.
616
617        // Step 7. Fetch request with processResponseConsumeBody set to the following steps given response response and null,
618        // failure, or a byte sequence bodyBytes: [..]
619        Some(request)
620    }
621
622    /// <https://html.spec.whatwg.org/multipage/#linked-resource-fetch-setup-steps>
623    fn linked_resource_fetch_setup(&self, request: &mut RequestBuilder) -> bool {
624        // https://html.spec.whatwg.org/multipage/#rel-icon:linked-resource-fetch-setup-steps
625        if self.relations.get().contains(LinkRelations::ICON) {
626            // Step 1. Set request's destination to "image".
627            request.destination = Destination::Image;
628
629            // Step 2. Return true.
630            //
631            // Fall-through
632        }
633
634        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:linked-resource-fetch-setup-steps
635        if self.relations.get().contains(LinkRelations::STYLESHEET) {
636            // Step 1. If el's disabled attribute is set, then return false.
637            if self
638                .upcast::<Element>()
639                .has_attribute(&local_name!("disabled"))
640            {
641                return false;
642            }
643            // Step 2. If el contributes a script-blocking style sheet, append el to its node document's script-blocking style sheet set.
644            //
645            // Implemented in `ElementStylesheetLoader::load_with_element`.
646
647            // Step 3. If el's media attribute's value matches the environment and el is potentially render-blocking, then block rendering on el.
648            //
649            // Implemented in `ElementStylesheetLoader::load_with_element`.
650
651            // Step 4. If el is currently render-blocking, then set request's render-blocking to true.
652            // TODO
653
654            // Step 5. Return true.
655            //
656            // Fall-through
657        }
658
659        true
660    }
661
662    /// The `fetch and process the linked resource` algorithm for [`rel="prefetch"`](https://html.spec.whatwg.org/multipage/#link-type-prefetch)
663    fn fetch_and_process_prefetch_link(&self, href: &str) {
664        // Step 1. If el's href attribute's value is the empty string, then return.
665        if href.is_empty() {
666            return;
667        }
668
669        // Step 2. Let options be the result of creating link options from el.
670        let mut options = self.processing_options();
671
672        // Step 3. Set options's destination to the empty string.
673        options.destination = Destination::None;
674
675        // Step 4. Let request be the result of creating a link request given options.
676        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            // Step 5. If request is null, then return.
683            return;
684        };
685        let url = request.url.url();
686
687        // Step 6. Set request's initiator to "prefetch".
688        let request = request.initiator(Initiator::Prefetch);
689
690        // (Step 7, firing load/error events is handled in the FetchResponseListener impl for LinkFetchContext)
691
692        // Step 8. The user agent should fetch request, with processResponseConsumeBody set to processPrefetchResponse.
693        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    /// <https://html.spec.whatwg.org/multipage/#concept-link-obtain>
704    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        // https://html.spec.whatwg.org/multipage/#processing-the-type-attribute
713        // > If the UA does not support the given MIME type for the given link relationship,
714        // > then the UA should not fetch and process the linked resource
715        //
716        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet
717        // > The default type for resources given by the stylesheet keyword is text/css.
718        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        // Step 1.
724        let href = element.get_string_attribute(&local_name!("href"));
725        if href.is_empty() {
726            return;
727        }
728
729        // Step 2.
730        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        // Step 3
739        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    /// <https://html.spec.whatwg.org/multipage/#attr-link-disabled>
770    fn handle_disabled_attribute_change(&self, no_gc: &NoGC, is_removal: bool) {
771        // > Whenever the disabled attribute is removed, set the link element's explicitly enabled attribute to true.
772        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 el's href attribute's value is the empty string, then return.
784        if href.is_empty() {
785            return;
786        }
787
788        // The spec does not specify this, but we don't fetch favicons for iframes, as
789        // they won't be displayed anyways.
790        let window = self.owner_window();
791        if !window.is_top_level() {
792            return;
793        }
794
795        // Use the document's encoding to parse the URL, as the favicon URL is not necessarily UTF-8.
796        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        // Ignore all previous fetch operations
802        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                // We don't care about metadata and such for favicons.
857                return;
858            };
859
860            if request_generation_id != link_element.get_request_generation_id() {
861                // This load is no longer relevant.
862                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                        // This load is no longer relevant.
874                        return;
875                    };
876
877                    element.owner_document().process_favicon_image(image, false);
878                }));
879        })
880    }
881
882    /// <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
883    /// and type matching destination steps of <https://html.spec.whatwg.org/multipage/#preload>
884    fn handle_preload_url(&self, no_gc: &NoGC) {
885        // Step 1. Update the source set for el.
886        self.source_set
887            .safe_borrow_mut(no_gc)
888            .update_source_set(no_gc, self.upcast::<Element>());
889        // Step 2. Let options be the result of creating link options from el.
890        let mut options = self.processing_options();
891        // Step 3. Let destination be the result of translating the keyword
892        // representing the state of el's as attribute.
893        let Some(destination) = self.compute_destination_for_attribute() else {
894            // Step 4. If destination is null, then return.
895            return;
896        };
897        // Step 5. Set options's destination to destination.
898        options.destination = destination;
899        // Steps for https://html.spec.whatwg.org/multipage/#preload
900        {
901            // Step 1. If options's type doesn't match options's destination, then return.
902            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        // Step 6. Preload options, with the following steps given a response response:
909        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    /// <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
918    pub(crate) fn fire_event_after_response(
919        &self,
920        cx: &mut JSContext,
921        response: Result<(), NetworkError>,
922    ) {
923        // Step 3.1 If response is a network error, fire an event named error at el.
924        // Otherwise, fire an event named load at el.
925        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    /// <https://html.spec.whatwg.org/multipage/#link-type-modulepreload:fetch-and-process-the-linked-resource-2>
933    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        // Step 1. If el's href attribute's value is the empty string, then return.
938        if href_attribute_value.is_empty() {
939            return;
940        }
941
942        // Step 2. Let destination be the current state of el's as attribute (a destination), or "script" if it is in no state.
943        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                // `Destination::from_str` will map an empty string to `Destination::None`
951                "" => None,
952                // "fetch" is a valid preload destination, but not for modules
953                "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        // A module preload destination is "json", "style", "text" or a script-like destination.
962        let is_a_modulepreload_destination = match destination {
963            Destination::Json | Destination::Style | Destination::Text => true,
964            // https://fetch.spec.whatwg.org/#ref-for-request-destination-script-like
965            // While "xslt" can cause script execution, it is not relevant here.
966            Destination::Xslt => false,
967            d => d.is_script_like(),
968        };
969
970        // Step 3. If destination is not a module preload destination, then queue an element task on the
971        // networking task source given el to fire an event named error at el, and return.
972        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        // Step 4. Let url be the result of encoding-parsing a URL given el's href attribute's value, relative to el's node document.
980        // Step 5. If url is failure, then return.
981        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        // Step 6. Let settings object be el's node document's relevant settings object.
987
988        // Step 7. Let credentials mode be the CORS settings attribute credentials mode for el's crossorigin attribute.
989        let credentials_mode = cors_settings_attribute_credential_mode(el);
990
991        // Step 8. Let cryptographic nonce be el.[[CryptographicNonce]].
992        let cryptographic_nonce = el.nonce_value();
993
994        // Step 9. Let integrity metadata be the value of el's integrity attribute, if it is specified, or the empty string otherwise.
995        // Step 10. If el does not have an integrity attribute, then set integrity metadata to
996        // the result of resolving a module integrity metadata with url and settings object.
997        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        // Step 11. Let referrer policy be the current state of el's referrerpolicy attribute.
1006        let referrer_policy = referrer_policy_for_element(el);
1007
1008        // Step 12. Let fetch priority be the current state of el's fetchpriority attribute.
1009        let fetch_priority = self.FetchPriority().into();
1010
1011        // Step 13. Let options be a script fetch options whose cryptographic nonce is cryptographic nonce,
1012        // integrity metadata is integrity metadata, parser metadata is "not-parser-inserted",
1013        // credentials mode is credentials mode, referrer policy is referrer policy, and fetch priority is fetch priority.
1014        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        // Step 14. Fetch a modulepreload module script graph given url, destination, settings object, options,
1027        // and with the following steps given result:
1028        fetch_a_modulepreload_module(
1029            cx,
1030            url,
1031            destination,
1032            &global,
1033            options,
1034            move |cx, fetch_failed| {
1035                // Step 1. If result is null, then fire an event named error at el, and return.
1036                // Step 2. Fire an event named load at el.
1037                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    /// <https://html.spec.whatwg.org/multipage/#potentially-render-blocking>
1074    fn potentially_render_blocking(&self) -> bool {
1075        // An element is potentially render-blocking if its blocking tokens set contains "render",
1076        // or if it is implicitly potentially render-blocking, which will be defined at the individual elements.
1077        // By default, an element is not implicitly potentially render-blocking.
1078        //
1079        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:implicitly-potentially-render-blocking
1080        // > A link element of this type is implicitly potentially render-blocking if the element was created by its node document's parser.
1081        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    // https://html.spec.whatwg.org/multipage/#dom-link-href
1107    make_url_getter!(Href, "href");
1108
1109    // https://html.spec.whatwg.org/multipage/#dom-link-href
1110    make_url_setter!(SetHref, "href");
1111
1112    // https://html.spec.whatwg.org/multipage/#dom-link-rel
1113    make_getter!(Rel, "rel");
1114
1115    /// <https://html.spec.whatwg.org/multipage/#dom-link-rel>
1116    fn SetRel(&self, cx: &mut JSContext, rel: DOMString) {
1117        self.upcast::<Element>()
1118            .set_tokenlist_attribute(cx, &local_name!("rel"), rel);
1119    }
1120
1121    // https://html.spec.whatwg.org/multipage/#dom-link-as
1122    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    // https://html.spec.whatwg.org/multipage/#dom-link-as
1134    make_setter!(SetAs, "as");
1135
1136    // https://html.spec.whatwg.org/multipage/#dom-link-media
1137    make_getter!(Media, "media");
1138
1139    // https://html.spec.whatwg.org/multipage/#dom-link-media
1140    make_setter!(SetMedia, "media");
1141
1142    // https://html.spec.whatwg.org/multipage/#dom-link-integrity
1143    make_getter!(Integrity, "integrity");
1144
1145    // https://html.spec.whatwg.org/multipage/#dom-link-integrity
1146    make_setter!(SetIntegrity, "integrity");
1147
1148    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
1149    make_getter!(Hreflang, "hreflang");
1150
1151    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
1152    make_setter!(SetHreflang, "hreflang");
1153
1154    // https://html.spec.whatwg.org/multipage/#dom-link-type
1155    make_getter!(Type, "type");
1156
1157    // https://html.spec.whatwg.org/multipage/#dom-link-type
1158    make_setter!(SetType, "type");
1159
1160    // https://html.spec.whatwg.org/multipage/#dom-link-imagesrcset
1161    make_url_getter!(ImageSrcset, "imagesrcset");
1162
1163    // https://html.spec.whatwg.org/multipage/#dom-link-imagesrcset
1164    make_url_setter!(SetImageSrcset, "imagesrcset");
1165
1166    // https://html.spec.whatwg.org/multipage/#dom-link-imagesizes
1167    make_getter!(ImageSizes, "imagesizes");
1168
1169    // https://html.spec.whatwg.org/multipage/#dom-link-imagesizes
1170    make_setter!(SetImageSizes, "imagesizes");
1171
1172    // https://html.spec.whatwg.org/multipage/#dom-link-disabled
1173    make_bool_getter!(Disabled, "disabled");
1174
1175    // https://html.spec.whatwg.org/multipage/#dom-link-disabled
1176    make_bool_setter!(SetDisabled, "disabled");
1177
1178    /// <https://html.spec.whatwg.org/multipage/#dom-link-rellist>
1179    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    // https://html.spec.whatwg.org/multipage/#dom-link-charset
1207    make_getter!(Charset, "charset");
1208
1209    // https://html.spec.whatwg.org/multipage/#dom-link-charset
1210    make_setter!(SetCharset, "charset");
1211
1212    // https://html.spec.whatwg.org/multipage/#dom-link-rev
1213    make_getter!(Rev, "rev");
1214
1215    // https://html.spec.whatwg.org/multipage/#dom-link-rev
1216    make_setter!(SetRev, "rev");
1217
1218    // https://html.spec.whatwg.org/multipage/#dom-link-target
1219    make_getter!(Target, "target");
1220
1221    // https://html.spec.whatwg.org/multipage/#dom-link-target
1222    make_setter!(SetTarget, "target");
1223
1224    /// <https://html.spec.whatwg.org/multipage/#attr-link-blocking>
1225    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    /// <https://html.spec.whatwg.org/multipage/#dom-link-crossorigin>
1237    fn GetCrossOrigin(&self) -> Option<DOMString> {
1238        reflect_cross_origin_attribute(self.upcast::<Element>())
1239    }
1240
1241    /// <https://html.spec.whatwg.org/multipage/#dom-link-crossorigin>
1242    fn SetCrossOrigin(&self, cx: &mut JSContext, value: Option<DOMString>) {
1243        set_cross_origin_attribute(cx, self.upcast::<Element>(), value);
1244    }
1245
1246    /// <https://html.spec.whatwg.org/multipage/#dom-link-referrerpolicy>
1247    fn ReferrerPolicy(&self) -> DOMString {
1248        reflect_referrer_policy_attribute(self.upcast::<Element>())
1249    }
1250
1251    // https://html.spec.whatwg.org/multipage/#dom-link-referrerpolicy
1252    make_setter!(SetReferrerPolicy, "referrerpolicy");
1253
1254    /// <https://drafts.csswg.org/cssom/#dom-linkstyle-sheet>
1255    fn GetSheet(&self, cx: &mut JSContext) -> Option<DomRoot<DOMStyleSheet>> {
1256        self.get_cssom_stylesheet(cx).map(DomRoot::upcast)
1257    }
1258
1259    // <https://html.spec.whatwg.org/multipage/#dom-link-fetchpriority>
1260    make_enumerated_getter!(
1261        FetchPriority,
1262        "fetchpriority",
1263        "high" | "low" | "auto",
1264        missing => "auto",
1265        invalid => "auto"
1266    );
1267    // https://html.spec.whatwg.org/multipage/#dom-link-fetchpriority
1268    make_setter!(SetFetchPriority, "fetchpriority");
1269}