Skip to main content

script/dom/html/document_metadata/
htmlmetaelement.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::str::FromStr;
6
7use content_security_policy::{Policy, PolicyDisposition, PolicySource};
8use dom_struct::dom_struct;
9use embedder_traits::Theme;
10use html5ever::{LocalName, Prefix, local_name};
11use js::context::JSContext;
12use js::rust::HandleObject;
13use net_traits::ReferrerPolicy;
14use paint_api::viewport_description::ViewportDescription;
15use script_bindings::dom::UnrootedDom;
16use servo_config::pref;
17use style::str::HTML_SPACE_CHARACTERS;
18
19use crate::dom::bindings::codegen::Bindings::HTMLMetaElementBinding::HTMLMetaElementMethods;
20use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
21use crate::dom::bindings::inheritance::Castable;
22use crate::dom::bindings::root::DomRoot;
23use crate::dom::bindings::str::DOMString;
24use crate::dom::document::Document;
25use crate::dom::element::attributes::storage::AttrRef;
26use crate::dom::element::{AttributeMutation, Element};
27use crate::dom::html::htmlelement::HTMLElement;
28use crate::dom::html::htmlheadelement::HTMLHeadElement;
29use crate::dom::iterators::ShadowIncluding;
30use crate::dom::node::virtualmethods::VirtualMethods;
31use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext};
32
33#[dom_struct]
34pub(crate) struct HTMLMetaElement {
35    htmlelement: HTMLElement,
36}
37
38impl HTMLMetaElement {
39    fn new_inherited(
40        local_name: LocalName,
41        prefix: Option<Prefix>,
42        document: &Document,
43    ) -> HTMLMetaElement {
44        HTMLMetaElement {
45            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
46        }
47    }
48
49    pub(crate) fn new(
50        cx: &mut js::context::JSContext,
51        local_name: LocalName,
52        prefix: Option<Prefix>,
53        document: &Document,
54        proto: Option<HandleObject>,
55    ) -> DomRoot<HTMLMetaElement> {
56        Node::reflect_node_with_proto(
57            cx,
58            Box::new(HTMLMetaElement::new_inherited(local_name, prefix, document)),
59            document,
60            proto,
61        )
62    }
63
64    fn process_attributes(&self, cx: &mut JSContext) {
65        let element = self.upcast::<Element>();
66        if let Some(ref name) = element.get_name() {
67            let name = name.trim_matches(HTML_SPACE_CHARACTERS);
68            if name.eq_ignore_ascii_case("referrer") {
69                self.apply_referrer();
70            }
71            if name.eq_ignore_ascii_case("viewport") {
72                self.parse_and_send_viewport_if_necessary(cx);
73            }
74        }
75        // https://html.spec.whatwg.org/multipage/#attr-meta-http-equiv
76        if !self.HttpEquiv().is_empty() {
77            // TODO: Implement additional http-equiv candidates
78            if self.HttpEquiv().eq_ignore_ascii_case("refresh") {
79                self.declarative_refresh();
80            } else if self
81                .HttpEquiv()
82                .eq_ignore_ascii_case("content-security-policy")
83            {
84                self.apply_csp_list();
85            } else if self.HttpEquiv().eq_ignore_ascii_case("content-language") {
86                self.pragma_set_default_language();
87            }
88        }
89    }
90
91    fn process_referrer_attribute(&self) {
92        let element = self.upcast::<Element>();
93        if let Some(ref name) = element.get_name() {
94            let name = name.trim_matches(HTML_SPACE_CHARACTERS);
95
96            if name.eq_ignore_ascii_case("referrer") {
97                self.apply_referrer();
98            }
99        }
100    }
101
102    /// <https://html.spec.whatwg.org/multipage/#meta-referrer>
103    fn apply_referrer(&self) {
104        let doc = self.owner_document();
105        // From spec: For historical reasons, unlike other standard metadata names, the processing model for referrer
106        // is not responsive to element removals, and does not use tree order. Only the most-recently-inserted or
107        // most-recently-modified meta element in this state has an effect.
108        // Step 1. If element is not in a document tree, then return.
109        let meta_node = self.upcast::<Node>();
110        if !meta_node.is_in_a_document_tree() {
111            return;
112        }
113
114        // Step 2. If element does not have a name attribute whose value is an ASCII
115        // case-insensitive match for "referrer", then return.
116        if self.upcast::<Element>().get_name() != Some(atom!("referrer")) {
117            return;
118        }
119
120        // Step 3. If element does not have a content attribute, or that attribute's value is the
121        // empty string, then return.
122        if let Some(content) = self
123            .upcast::<Element>()
124            .get_attribute_string_value(&local_name!("content"))
125            .filter(|value| !value.is_empty())
126        {
127            // Step 4. Let value be the value of element's content attribute, converted to ASCII
128            // lowercase.
129            // Step 5. If value is one of the values given in the first column of the following
130            // table, then set value to the value given in the second column:
131            // Step 6. If value is a referrer policy, then set element's node document's policy
132            // container's referrer policy to policy.
133            doc.set_referrer_policy(ReferrerPolicy::from_with_legacy(&content));
134        }
135    }
136
137    /// <https://drafts.csswg.org/css-viewport/#parsing-algorithm>
138    fn parse_and_send_viewport_if_necessary(&self, cx: &mut JSContext) {
139        if !pref!(viewport_meta_enabled) {
140            return;
141        }
142
143        // Skip processing if this isn't the top level frame
144        if !self.owner_window().is_top_level() {
145            return;
146        }
147        let element = self.upcast::<Element>();
148        let Some(content) = element.get_attribute_string_value(&local_name!("content")) else {
149            return;
150        };
151
152        if let Ok(viewport) = ViewportDescription::from_str(&content) {
153            let initial_scale = viewport.initial_scale.get();
154            let window = self.owner_window();
155            window.paint_api().viewport(window.webview_id(), viewport);
156            window
157                .get_or_init_visual_viewport(cx)
158                .update_scale(initial_scale);
159        }
160    }
161
162    /// <https://html.spec.whatwg.org/multipage/#meta-color-scheme>
163    fn obtain_page_supported_color_schemes(&self, cx: &mut JSContext) {
164        let doc = self.owner_document();
165        // Step 1. Let candidate elements be the list of all meta elements
166        // that meet the following criteria, in tree order:
167        let new_theme = doc
168            .upcast::<Node>()
169            // Do not traverse shadow trees for optimization, which also implies:
170            // > the element is in a document tree;
171            .traverse_preorder_non_rooting(cx.no_gc(), ShadowIncluding::No)
172            .filter_map(UnrootedDom::downcast::<HTMLMetaElement>)
173            .filter_map(|meta| {
174                let element = UnrootedDom::upcast::<Element>(meta);
175
176                // > the element has a content attribute.
177                element
178                    .get_attribute_string_value(&local_name!("content"))
179                    .filter(|_| {
180                        // > the element has a name attribute,
181                        // > whose value is an ASCII case-insensitive match for color-scheme; and
182                        element.get_name().is_color_scheme()
183                    })
184            })
185            // Step 2. For each element in candidate elements:
186            .find_map(|content| {
187                // Step 2.1. Let parsed be the result of parsing a list of
188                // component values given the value of element's content attribute.
189                // Step 2.2. If parsed is a valid CSS 'color-scheme' property value,
190                // then return parsed.
191                // TODO: Allow for more different themes than the ones that embedders can set
192                if content.eq_ignore_ascii_case("dark") {
193                    Some(Theme::Dark)
194                } else if content.eq_ignore_ascii_case("light") {
195                    Some(Theme::Light)
196                } else {
197                    // Step 3. Return null.
198                    None
199                }
200            });
201
202        doc.set_theme(new_theme);
203    }
204
205    /// <https://html.spec.whatwg.org/multipage/#attr-meta-http-equiv-content-security-policy>
206    fn apply_csp_list(&self) {
207        // Step 1. If the meta element is not a child of a head element, return.
208        if self
209            .upcast::<Node>()
210            .GetParentElement()
211            .is_none_or(|parent| !parent.is::<HTMLHeadElement>())
212        {
213            return;
214        };
215        // Step 2. If the meta element has no content attribute, or if that attribute's value is the empty string, then return.
216        let Some(content) = self
217            .upcast::<Element>()
218            .get_attribute_string_value(&local_name!("content"))
219        else {
220            return;
221        };
222        if content.is_empty() {
223            return;
224        }
225        // Step 3. Let policy be the result of executing Content Security Policy's
226        // parse a serialized Content Security Policy algorithm
227        // on the meta element's content attribute's value,
228        // with a source of "meta", and a disposition of "enforce".
229        let mut policy = Policy::parse(&content, PolicySource::Meta, PolicyDisposition::Enforce);
230        // Step 4. Remove all occurrences of the report-uri, frame-ancestors,
231        // and sandbox directives from policy.
232        policy.directive_set.retain(|directive| {
233            !matches!(
234                directive.name.as_str(),
235                "report-uri" | "frame-ancestors" | "sandbox"
236            )
237        });
238        // Step 5. Enforce the policy policy.
239        self.owner_document().enforce_csp_policy(policy);
240    }
241
242    /// <https://html.spec.whatwg.org/multipage/#shared-declarative-refresh-steps>
243    fn declarative_refresh(&self) {
244        if !self.upcast::<Node>().is_in_a_document_tree() {
245            return;
246        }
247
248        // Step 2. Let input be the value of the element's content attribute.
249        let content = self.Content();
250        // Step 1. If the meta element has no content attribute, or if that attribute's value is the empty string, then return.
251        if !content.is_empty() {
252            // Step 3. Run the shared declarative refresh steps with the meta element's node document, input, and the meta element.
253            self.owner_document().shared_declarative_refresh_steps(
254                &content.as_bytes(),
255                /* from_meta_element */ true,
256            );
257        }
258    }
259
260    /// <https://html.spec.whatwg.org/multipage/#pragma-set-default-language>
261    fn pragma_set_default_language(&self) {
262        // Step 3. Let input be the value of the element's content attribute.
263        let input = self.Content();
264        let input = input.str();
265        // Step 2. If the element's content attribute contains
266        // a U+002C COMMA character (,), then return.
267        let candidate = if input.contains('\u{002C}') {
268            None
269        } else {
270            // Step 1. If the meta element has no content attribute, then return.
271            // Step 4. Let position point at the first character of input.
272            // Step 5. Skip ASCII whitespace within input given position.
273            // Step 6. Collect a sequence of code points that are
274            // not ASCII whitespace from input given position.
275            // Step 7. Let candidate be the string that resulted from the previous step.
276            // Step 8. If candidate is the empty string, return.
277            input
278                .trim_start()
279                .split_ascii_whitespace()
280                .next()
281                .filter(|candidate| !candidate.is_empty())
282                .map(|candidate| candidate.to_owned())
283        };
284
285        // Step 9. Set the pragma-set default language to candidate.
286        self.owner_document().set_default_language(candidate);
287    }
288}
289
290impl HTMLMetaElementMethods<crate::DomTypeHolder> for HTMLMetaElement {
291    // https://html.spec.whatwg.org/multipage/#dom-meta-name
292    make_getter!(Name, "name");
293
294    // https://html.spec.whatwg.org/multipage/#dom-meta-name
295    make_atomic_setter!(SetName, "name");
296
297    // https://html.spec.whatwg.org/multipage/#dom-meta-content
298    make_getter!(Content, "content");
299
300    // https://html.spec.whatwg.org/multipage/#dom-meta-content
301    make_setter!(SetContent, "content");
302
303    // https://html.spec.whatwg.org/multipage/#dom-meta-httpequiv
304    make_getter!(HttpEquiv, "http-equiv");
305    // https://html.spec.whatwg.org/multipage/#dom-meta-httpequiv
306    make_atomic_setter!(SetHttpEquiv, "http-equiv");
307
308    // https://html.spec.whatwg.org/multipage/#dom-meta-scheme
309    make_getter!(Scheme, "scheme");
310    // https://html.spec.whatwg.org/multipage/#dom-meta-scheme
311    make_setter!(SetScheme, "scheme");
312}
313
314impl VirtualMethods for HTMLMetaElement {
315    fn super_type(&self) -> Option<&dyn VirtualMethods> {
316        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
317    }
318
319    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
320        if let Some(s) = self.super_type() {
321            s.bind_to_tree(cx, context);
322        }
323
324        if context.tree_connected {
325            self.process_attributes(cx);
326
327            // Optimization: only if this meta element has a color scheme we should update.
328            // Otherwise we would traverse the whole DOM for any meta element, which are
329            // commonly used for information for crawlers.
330            if self.upcast::<Element>().get_name().is_color_scheme() {
331                // https://html.spec.whatwg.org/multipage/#meta-color-scheme
332                // > If any meta elements are inserted into the document or removed from the document,
333                // > or existing meta elements have their name or content attributes changed,
334                // > user agents must re-run the above algorithm.
335                //
336                // When the element is inserted
337                self.obtain_page_supported_color_schemes(cx);
338            }
339        }
340    }
341
342    fn attribute_mutated(
343        &self,
344        cx: &mut js::context::JSContext,
345        attr: AttrRef<'_>,
346        mutation: AttributeMutation,
347    ) {
348        if let Some(s) = self.super_type() {
349            s.attribute_mutated(cx, attr, mutation);
350        }
351
352        self.process_referrer_attribute();
353
354        // Optimization: only if this meta element either did or does now specify a color-scheme.
355        // Or if the content of a meta element is changed that specifies a color-scheme
356        // Otherwise we would traverse the whole DOM for any meta element, which are
357        // commonly used for information for crawlers.
358        let affects_color_scheme = if *attr.local_name() == local_name!("name") {
359            mutation.old_value(attr).is_color_scheme() || mutation.new_value(attr).is_color_scheme()
360        } else {
361            self.upcast::<Element>().get_name().is_color_scheme() &&
362                *attr.local_name() == local_name!("content")
363        };
364
365        if affects_color_scheme {
366            // https://html.spec.whatwg.org/multipage/#meta-color-scheme
367            // > If any meta elements are inserted into the document or removed from the document,
368            // > or existing meta elements have their name or content attributes changed,
369            // > user agents must re-run the above algorithm.
370            //
371            // When the content attribute has changed
372            self.obtain_page_supported_color_schemes(cx);
373        }
374    }
375
376    fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
377        if let Some(s) = self.super_type() {
378            s.unbind_from_tree(cx, context);
379        }
380
381        if context.tree_connected {
382            self.process_referrer_attribute();
383
384            // Optimization: only if this meta element has a color scheme we should update.
385            // Otherwise we would traverse the whole DOM for any meta element, which are
386            // commonly used for information for crawlers.
387            if self.upcast::<Element>().get_name().is_color_scheme() {
388                // https://html.spec.whatwg.org/multipage/#meta-color-scheme
389                // > If any meta elements are inserted into the document or removed from the document,
390                // > or existing meta elements have their name or content attributes changed,
391                // > user agents must re-run the above algorithm.
392                //
393                // When the element is removed
394                self.obtain_page_supported_color_schemes(cx);
395            }
396        }
397    }
398}
399
400/// Trait to make it easier to make sure all callers lowercase to ASCII
401/// before comparing to the `color-scheme` value.
402/// Otherwise it is easy to miss one usage and compare case-sensitively.
403trait IsColorSchemeValue {
404    fn is_color_scheme(&self) -> bool;
405}
406
407impl<T: AsRef<str>> IsColorSchemeValue for Option<T> {
408    fn is_color_scheme(&self) -> bool {
409        self.as_ref()
410            .is_some_and(|name| name.as_ref().eq_ignore_ascii_case("color-scheme"))
411    }
412}