script/dom/
trustedscripturl.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::fmt;
6
7use dom_struct::dom_struct;
8
9use crate::dom::bindings::codegen::Bindings::TrustedScriptURLBinding::TrustedScriptURLMethods;
10use crate::dom::bindings::codegen::UnionTypes::TrustedScriptURLOrUSVString;
11use crate::dom::bindings::error::Fallible;
12use crate::dom::bindings::reflector::{Reflector, reflect_dom_object};
13use crate::dom::bindings::root::DomRoot;
14use crate::dom::bindings::str::DOMString;
15use crate::dom::globalscope::GlobalScope;
16use crate::dom::trustedtypepolicy::TrustedType;
17use crate::dom::trustedtypepolicyfactory::{DEFAULT_SCRIPT_SINK_GROUP, TrustedTypePolicyFactory};
18use crate::script_runtime::CanGc;
19
20#[dom_struct]
21pub struct TrustedScriptURL {
22    reflector_: Reflector,
23
24    data: DOMString,
25}
26
27impl TrustedScriptURL {
28    fn new_inherited(data: DOMString) -> Self {
29        Self {
30            reflector_: Reflector::new(),
31            data,
32        }
33    }
34
35    pub(crate) fn new(data: DOMString, global: &GlobalScope, can_gc: CanGc) -> DomRoot<Self> {
36        reflect_dom_object(Box::new(Self::new_inherited(data)), global, can_gc)
37    }
38
39    pub(crate) fn get_trusted_script_url_compliant_string(
40        global: &GlobalScope,
41        value: TrustedScriptURLOrUSVString,
42        containing_class: &str,
43        field: &str,
44        can_gc: CanGc,
45    ) -> Fallible<DOMString> {
46        match value {
47            TrustedScriptURLOrUSVString::USVString(value) => {
48                let sink = format!("{} {}", containing_class, field);
49                TrustedTypePolicyFactory::get_trusted_type_compliant_string(
50                    TrustedType::TrustedScriptURL,
51                    global,
52                    value.as_ref().into(),
53                    &sink,
54                    DEFAULT_SCRIPT_SINK_GROUP,
55                    can_gc,
56                )
57            },
58            TrustedScriptURLOrUSVString::TrustedScriptURL(trusted_script_url) => {
59                Ok(trusted_script_url.data.clone())
60            },
61        }
62    }
63
64    pub(crate) fn data(&self) -> &DOMString {
65        &self.data
66    }
67}
68
69impl fmt::Display for TrustedScriptURL {
70    #[inline]
71    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72        f.write_str(&self.data.str())
73    }
74}
75
76impl TrustedScriptURLMethods<crate::DomTypeHolder> for TrustedScriptURL {
77    /// <https://www.w3.org/TR/trusted-types/#trustedscripturl-stringification-behavior>
78    fn Stringifier(&self) -> DOMString {
79        self.data.clone()
80    }
81
82    /// <https://www.w3.org/TR/trusted-types/#dom-trustedscripturl-tojson>
83    fn ToJSON(&self) -> DOMString {
84        self.data.clone()
85    }
86}