Skip to content

Truly independent web browser

LibWeb: Process SVG script elements with the HTML script algorithms

Tim Ledbettera15c1ab6882d
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index d73806180fa..74c36d01cc3 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -1051,7 +1051,6 @@ void Document::visit_edges(Cell::Visitor& visitor)
visitor.visit(m_associated_inert_template_document);
visitor.visit(m_appropriate_template_contents_owner_document);
visitor.visit(m_pending_parsing_blocking_script);
- visitor.visit(m_pending_parsing_blocking_svg_script);
visitor.visit(m_history);
visitor.visit(m_html_parser_end_state);
visitor.visit(m_ongoing_navigation_fetch);
@@ -1656,12 +1655,9 @@ WebIDL::ExceptionOr<Document*> Document::open(Optional<Utf16String> const&, Opti
// delaying the replacement document's load event before removing them from the parser's queues.
if (auto* pending_parsing_blocking_script = this->pending_parsing_blocking_script())
pending_parsing_blocking_script->stop_delaying_document_load_event({});
- if (m_pending_parsing_blocking_svg_script)
- m_pending_parsing_blocking_svg_script->stop_delaying_document_load_event({});
for (auto& script : m_scripts_to_execute_when_parsing_has_finished)
as<HTML::HTMLOrSVGScriptElement>(*script).stop_delaying_document_load_event({});
m_pending_parsing_blocking_script = nullptr;
- m_pending_parsing_blocking_svg_script = nullptr;
m_scripts_to_execute_when_parsing_has_finished.clear();
// 16. Create an HTML parser whose allow declarative shadow roots is document's allow declarative shadow roots, and
@@ -4118,19 +4114,6 @@ HTML::HTMLOrSVGScriptElement& Document::take_pending_parsing_blocking_script(Bad
return as<HTML::HTMLOrSVGScriptElement>(*script);
}
-void Document::set_pending_parsing_blocking_svg_script(SVG::SVGScriptElement* script)
-{
- m_pending_parsing_blocking_svg_script = script;
-}
-
-GC::Ref<SVG::SVGScriptElement> Document::take_pending_parsing_blocking_svg_script(Badge<HTML::HTMLParser>)
-{
- VERIFY(m_pending_parsing_blocking_svg_script);
- auto script = m_pending_parsing_blocking_svg_script;
- m_pending_parsing_blocking_svg_script = nullptr;
- return *script;
-}
-
Variant<GC::Ref<HTML::HTMLScriptElement>, GC::Ref<SVG::SVGScriptElement>, Empty> Document::current_script_for_bindings() const
{
if (auto* html_script_element = as_if<HTML::HTMLScriptElement>(m_current_script.ptr()))
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index 38efd101ab5..e331d987e8d 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -738,14 +738,7 @@ public:
void set_pending_parsing_blocking_script(HTML::HTMLOrSVGScriptElement*);
HTML::HTMLOrSVGScriptElement* pending_parsing_blocking_script();
HTML::HTMLOrSVGScriptElement& take_pending_parsing_blocking_script(Badge<HTML::HTMLParser>);
-
- void set_pending_parsing_blocking_svg_script(SVG::SVGScriptElement*);
- SVG::SVGScriptElement* pending_parsing_blocking_svg_script() { return m_pending_parsing_blocking_svg_script.ptr(); }
- GC::Ref<SVG::SVGScriptElement> take_pending_parsing_blocking_svg_script(Badge<HTML::HTMLParser>);
- bool has_pending_parsing_blocking_script() const
- {
- return m_pending_parsing_blocking_script.ptr() || m_pending_parsing_blocking_svg_script.ptr();
- }
+ bool has_pending_parsing_blocking_script() const { return m_pending_parsing_blocking_script.ptr(); }
void add_script_to_execute_when_parsing_has_finished(Badge<HTML::HTMLOrSVGScriptElement>, HTML::HTMLOrSVGScriptElement&);
Vector<GC::Ref<Element>>& scripts_to_execute_when_parsing_has_finished() { return m_scripts_to_execute_when_parsing_has_finished; }
@@ -2066,7 +2059,6 @@ private:
Utf16String m_source;
GC::Ptr<Element> m_pending_parsing_blocking_script;
- GC::Ptr<SVG::SVGScriptElement> m_pending_parsing_blocking_svg_script;
Vector<GC::Ref<Element>> m_scripts_to_execute_when_parsing_has_finished;
diff --git a/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cpp b/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cpp
index 54b420bb7bb..2601981874c 100644
--- a/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.cpp
@@ -25,6 +25,7 @@
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
+#include <LibWeb/SVG/SVGScriptElement.h>
#include <LibWeb/SVG/SVGUseElement.h>
#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
@@ -72,7 +73,7 @@ WebIDL::ExceptionOr<void> HTMLOrSVGScriptElement::prepare_script_text()
auto& element = as_element();
// 1. Let sink be "HTMLScriptElement text" if script is an HTMLScriptElement; otherwise "SVGScriptElement text".
- constexpr auto sink = TrustedTypes::InjectionSink::HTMLScriptElement_text;
+ auto sink = is<HTMLScriptElement>(element) ? TrustedTypes::InjectionSink::HTMLScriptElement_text : TrustedTypes::InjectionSink::SVGScriptElement_text;
// 2. If script’s script text value is not equal to its child text content,
// set script’s script text to the result of executing get Trusted Type compliant string, with the following arguments:
@@ -746,6 +747,8 @@ HTML::HTMLOrSVGScriptElement* Node::fast_as<HTML::HTMLOrSVGScriptElement>()
{
if (auto* html_script_element = as_if<HTML::HTMLScriptElement>(*this))
return html_script_element;
+ if (auto* svg_script_element = as_if<SVG::SVGScriptElement>(*this))
+ return svg_script_element;
return nullptr;
}
diff --git a/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.h b/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.h
index 6d75ebcac76..a3b8c74a781 100644
--- a/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.h
+++ b/Libraries/LibWeb/HTML/HTMLOrSVGScriptElement.h
@@ -180,7 +180,7 @@ private:
namespace Web::DOM {
template<>
-inline bool Node::fast_is<HTML::HTMLOrSVGScriptElement>() const { return is_html_script_element(); }
+inline bool Node::fast_is<HTML::HTMLOrSVGScriptElement>() const { return is_html_script_element() || is_svg_script_element(); }
template<>
WEB_API HTML::HTMLOrSVGScriptElement* Node::fast_as<HTML::HTMLOrSVGScriptElement>();
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index e79acc6cf94..ce8c02413dc 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -191,7 +191,6 @@ extern "C" size_t ladybird_html_parser_child_at_index(size_t, size_t);
extern "C" u32 ladybird_html_parser_declarative_shadow_root_attributes(size_t);
extern "C" void ladybird_html_parser_remove_node(size_t);
extern "C" void ladybird_html_parser_handle_element_popped(size_t);
-extern "C" void ladybird_html_parser_prepare_svg_script(void*, size_t, size_t);
extern "C" void ladybird_html_parser_set_script_source_line(void*, size_t, size_t);
extern "C" void ladybird_html_parser_mark_script_already_started(void*, size_t);
extern "C" void ladybird_html_parser_process_meta_element(void*, size_t);
@@ -344,15 +343,16 @@ void HTMLParser::set_sanitizer_configuration(SanitizerConfiguration const& confi
void HTMLParser::configure_element_created_by_rust_parser(DOM::Element& element)
{
- if (element.local_name() != HTML::TagNames::script || element.namespace_uri() != Namespace::HTML)
+ // AD-HOC: The parser sets up SVG script elements like HTML script elements, matching other engines.
+ auto* script_element = as_if<HTMLOrSVGScriptElement>(element);
+ if (!script_element)
return;
- auto& script_element = as<HTMLScriptElement>(element);
if (!m_parsing_fragment && m_scripting_mode != ParserScriptingMode::Fragment)
- script_element.set_parser_document(Badge<HTMLParser> {}, document());
- script_element.set_force_async(Badge<HTMLParser> {}, false);
+ script_element->set_parser_document(Badge<HTMLParser> {}, document());
+ script_element->set_force_async(Badge<HTMLParser> {}, false);
if (m_parsing_fragment && m_scripting_mode != ParserScriptingMode::Fragment)
- script_element.set_already_started(Badge<HTMLParser> {}, true);
+ script_element->set_already_started(Badge<HTMLParser> {}, true);
}
GC::Ref<DOM::Element> HTMLParser::create_element_for_rust_parser(Utf16FlyString const& local_name, ReadonlySpan<RustFfiHtmlParserAttribute> attributes, Optional<Utf16FlyString> const& namespace_, DOM::Node& intended_parent, bool had_duplicate_attribute, GC::Ptr<HTMLFormElement> form_element, bool has_template_element_on_stack)
@@ -451,28 +451,10 @@ bool HTMLParser::process_script_end_tag_from_rust_parser(HTMLScriptElement& scri
return m_parser_pause_flag;
}
-void HTMLParser::prepare_svg_script_for_rust_parser(SVG::SVGScriptElement& script, size_t source_line_number)
-{
- // AD-HOC: For SVG script elements, set the parser-inserted flag before the element is inserted into the DOM.
- // Otherwise inserted()/attribute_changed() would invoke process_the_script_element() with the flag still unset
- // and bypass the parser-blocking fetch handling.
- //
- // https://html.spec.whatwg.org/multipage/parsing.html#scripting-mode
- // The Fragment scripting mode treats parser-inserted scripts as if they were not parser-inserted, allowing, for
- // example, executing scripts when applying a fragment created by createContextualFragment().
- if (m_scripting_mode != ParserScriptingMode::Fragment)
- script.set_parser_inserted({});
- script.set_source_line_number({}, source_line_number);
-}
-
void HTMLParser::set_script_source_line_from_rust_parser(DOM::Element& element, size_t source_line_number)
{
- if (auto* html_script_element = as_if<HTML::HTMLScriptElement>(element)) {
- html_script_element->set_source_line_number({}, source_line_number);
- return;
- }
- if (auto* svg_script_element = as_if<SVG::SVGScriptElement>(element))
- svg_script_element->set_source_line_number({}, source_line_number);
+ if (auto* script_element = as_if<HTMLOrSVGScriptElement>(element))
+ script_element->set_source_line_number({}, source_line_number);
}
void HTMLParser::mark_script_already_started_from_rust_parser(HTMLScriptElement& script)
@@ -594,9 +576,14 @@ bool HTMLParser::process_svg_script_end_tag_from_rust_parser(SVG::SVGScriptEleme
// Set the parser pause flag to true.
m_parser_pause_flag = true;
+ // https://w3c.github.io/trusted-types/dist/spec/#setting-slot-values-from-parser
+ // Set script’s script text value to its child text content.
+ script.set_script_text_from_parser();
+
// If the active speculative HTML parser is null and the user agent supports SVG, then Process the SVG script element according to the SVG rules. [SVG]
// The active speculative HTML parser is null here.
- script.process_the_script_element();
+ // NB: SVG defines the SVG script element as equivalent to the HTML script element, so it is prepared as one.
+ script.prepare_script(Badge<HTMLParser> {});
// Decrement the parser's script nesting level by one.
decrement_script_nesting_level();
@@ -611,7 +598,7 @@ bool HTMLParser::process_svg_script_end_tag_from_rust_parser(SVG::SVGScriptEleme
// If the SVG script registered itself as a pending parsing-blocking script (external fetch in flight),
// pause the parser and schedule a resume check. The parser will resume from
// resume_after_parser_blocking_script when the fetch completes.
- if (!m_parsing_fragment && document().pending_parsing_blocking_svg_script()) {
+ if (!m_parsing_fragment && document().pending_parsing_blocking_script()) {
// AD-HOC: Start the speculative HTML parser while the script blocks the parser, as for an HTML script.
if (script_nesting_level() == 0)
start_the_speculative_html_parser();
@@ -1316,13 +1303,7 @@ void HTMLParser::resume_after_parser_blocking_script()
return;
auto pending = document().pending_parsing_blocking_script();
- auto pending_svg = document().pending_parsing_blocking_svg_script();
- bool ready = false;
- if (pending)
- ready = pending->is_ready_to_be_parser_executed();
- else if (pending_svg)
- ready = pending_svg->is_ready_to_be_parser_executed();
- else
+ if (!pending)
return;
// 5. If the parser's Document has a style sheet that is blocking scripts or the script's ready to be
@@ -1332,7 +1313,7 @@ void HTMLParser::resume_after_parser_blocking_script()
// relevant state changes.
if (m_document->has_a_style_sheet_that_is_blocking_scripts())
return;
- if (!ready)
+ if (!pending->is_ready_to_be_parser_executed())
return;
// 3. Start the speculative HTML parser for this instance of the HTML parser.
@@ -1368,10 +1349,7 @@ void HTMLParser::resume_after_parser_blocking_script()
// 1. Let the script be the pending parsing-blocking script.
// 2. Set the pending parsing-blocking script to null.
// 11. Execute the script element the script.
- if (pending)
- document().take_pending_parsing_blocking_script({}).execute_script();
- else
- document().take_pending_parsing_blocking_svg_script({})->execute_pending_parser_blocking_script({});
+ document().take_pending_parsing_blocking_script({}).execute_script();
// 12. Decrement the parser's script nesting level by one.
decrement_script_nesting_level();
@@ -3115,11 +3093,6 @@ extern "C" void ladybird_html_parser_handle_element_popped(size_t element)
MUST(option_element->maybe_clone_into_selectedcontent());
}
-extern "C" void ladybird_html_parser_prepare_svg_script(void* parser, size_t element, size_t source_line_number)
-{
- parser_from_html_parser_ffi(parser).prepare_svg_script_for_rust_parser(as<SVG::SVGScriptElement>(node_from_html_parser_ffi(element)), source_line_number);
-}
-
extern "C" void ladybird_html_parser_set_script_source_line(void* parser, size_t element, size_t source_line_number)
{
parser_from_html_parser_ffi(parser).set_script_source_line_from_rust_parser(as<DOM::Element>(node_from_html_parser_ffi(element)), source_line_number);
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.h b/Libraries/LibWeb/HTML/Parser/HTMLParser.h
index 35dbed1ecf7..aa3ec2109f4 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.h
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.h
@@ -92,7 +92,6 @@ public:
void configure_element_created_by_rust_parser(DOM::Element&);
GC::Ref<DOM::Element> create_element_for_rust_parser(Utf16FlyString const&, ReadonlySpan<RustFfiHtmlParserAttribute>, Optional<Utf16FlyString> const& namespace_, DOM::Node& intended_parent, bool had_duplicate_attribute, GC::Ptr<HTMLFormElement>, bool has_template_element_on_stack);
- void prepare_svg_script_for_rust_parser(SVG::SVGScriptElement&, size_t source_line_number);
void set_script_source_line_from_rust_parser(DOM::Element&, size_t source_line_number);
void mark_script_already_started_from_rust_parser(HTMLScriptElement&);
void process_meta_element_from_rust_parser(HTMLMetaElement&);
diff --git a/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs b/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs
index 74f7b106704..7b5f95a6dd2 100644
--- a/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs
+++ b/Libraries/LibWeb/HTML/Parser/Rust/src/parser.rs
@@ -131,7 +131,6 @@ unsafe extern "C" {
);
fn ladybird_html_parser_remove_node(node: usize);
fn ladybird_html_parser_handle_element_popped(element: usize);
- fn ladybird_html_parser_prepare_svg_script(parser: *mut c_void, element: usize, source_line_number: usize);
fn ladybird_html_parser_set_script_source_line(parser: *mut c_void, element: usize, source_line_number: usize);
fn ladybird_html_parser_mark_script_already_started(parser: *mut c_void, element: usize);
fn ladybird_html_parser_process_meta_element(parser: *mut c_void, element: usize);
@@ -3530,13 +3529,10 @@ impl TreeBuilder {
&attributes.attributes,
token.had_duplicate_attribute(),
);
- if local_name == tag_name!("script") {
- let source_line_number = source_line_number_for_script_token(token);
- if namespace_ == RustFfiHtmlNamespace::Svg {
- self.prepare_svg_script(element, source_line_number);
- } else if namespace_ == RustFfiHtmlNamespace::Html {
- self.set_script_source_line(element, source_line_number);
- }
+ if local_name == tag_name!("script")
+ && (namespace_ == RustFfiHtmlNamespace::Html || namespace_ == RustFfiHtmlNamespace::Svg)
+ {
+ self.set_script_source_line(element, source_line_number_for_script_token(token));
}
self.recycle_attribute_buffers(attributes);
// 2. Insert an element at the adjusted insertion location with element.
@@ -3870,10 +3866,6 @@ impl TreeBuilder {
}
}
- fn prepare_svg_script(&mut self, element: usize, source_line_number: usize) {
- unsafe { ladybird_html_parser_prepare_svg_script(self.host, element, source_line_number) }
- }
-
fn set_script_source_line(&mut self, element: usize, source_line_number: usize) {
unsafe { ladybird_html_parser_set_script_source_line(self.host, element, source_line_number) }
}
diff --git a/Libraries/LibWeb/SVG/SVGScriptElement.cpp b/Libraries/LibWeb/SVG/SVGScriptElement.cpp
index de7080b1c83..5879092e3e2 100644
--- a/Libraries/LibWeb/SVG/SVGScriptElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGScriptElement.cpp
@@ -5,19 +5,12 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/ScopeGuard.h>
-#include <AK/Utf16String.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/HTML/AttributeNames.h>
#include <LibWeb/HTML/CORSSettingAttribute.h>
-#include <LibWeb/HTML/HTMLScriptElement.h>
-#include <LibWeb/HTML/Scripting/ClassicScript.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/Fetching.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/SVG/AttributeNames.h>
#include <LibWeb/SVG/SVGScriptElement.h>
-#include <LibWebCommon/MimeSniff/MimeType.h>
namespace Web::SVG {
@@ -32,204 +25,65 @@ void SVGScriptElement::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
SVGURIReferenceMixin::visit_edges(visitor);
- visitor.visit(m_preparation_time_document);
- visitor.visit(m_script);
+ visit_script_element_edges(visitor);
}
void SVGScriptElement::adopted_from(DOM::Document& old_document)
{
Base::adopted_from(old_document);
-
- if (m_document_load_event_delayer.has_value())
- m_document_load_event_delayer.emplace(document());
+ retarget_script_load_event_delayer(document());
}
void SVGScriptElement::attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_)
{
Base::attribute_changed(name, old_value, value, namespace_);
- if (name == SVG::AttributeNames::href || name == SVG::AttributeNames::type) {
- process_the_script_element();
- }
-}
-void SVGScriptElement::inserted()
-{
- Base::inserted();
- if (m_parser_inserted)
- return;
+ if (name == SVG::AttributeNames::href && (!namespace_.has_value() || namespace_ == Namespace::XLink)) {
+ if (value.has_value() && is_connected())
+ post_connection();
+ }
- process_the_script_element();
+ script_element_attribute_changed(name);
}
void SVGScriptElement::children_changed(ChildrenChangedMetadata const& metadata)
{
Base::children_changed(metadata);
- if (m_parser_inserted)
- return;
-
- process_the_script_element();
+ script_element_children_changed(metadata);
}
-// https://www.w3.org/TR/SVGMobile12/script.html#ScriptContentProcessing
-void SVGScriptElement::process_the_script_element()
+void SVGScriptElement::post_connection()
{
- // 1. If the 'script' element's "already processed" flag is true or if the element is not in the
- // document tree, then no action is performed and these steps are ended.
- if (m_already_processed || !in_a_document_tree())
- return;
-
- // https://html.spec.whatwg.org/multipage/webappapis.html#enabling-and-disabling-scripting
- if (is_scripting_disabled())
- return;
-
- // https://svgwg.org/svg2-draft/interact.html#ScriptElement
- // Before attempting to execute the ‘script’ element the resolved media type value for ‘type’ must be inspected.
- // If the SVG user agent does not support the scripting language then the ‘script’ element must not be executed.
- // FIXME: Support type="module" scripts
- auto maybe_script_type = attribute(SVG::AttributeNames::type);
- if (maybe_script_type.has_value() && !maybe_script_type->is_empty()) {
- auto script_type = maybe_script_type->to_ascii_lowercase().trim_ascii_whitespace();
- if (!MimeSniff::is_javascript_mime_type_essence_match(script_type)) {
- dbgln("SVGScriptElement: Unsupported script type: {}", *maybe_script_type);
- return;
- }
- }
-
- // https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element
- // 16. Set el's preparation-time document to its node document.
- m_preparation_time_document = document();
-
- // 2. If the 'script' element references external script content, then the external script content
- // using the current value of the 'xlink:href' attribute is fetched. Further processing of the
- // 'script' element is dependent on the external script content, and will block here until the
- // resource has been fetched or is determined to be an invalid IRI reference.
- if (has_attribute(SVG::AttributeNames::href) || has_attribute_ns(Namespace::XLink, SVG::AttributeNames::href)) {
- auto href_value = href()->base_val();
-
- auto maybe_script_url = document().encoding_parse_url(href_value);
- if (!maybe_script_url.has_value()) {
- dbgln("Invalid script URL: {}", href_value);
- return;
- }
- auto script_url = maybe_script_url.release_value();
-
- // https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element
- // 23. If el has a charset attribute, then let encoding be the result of getting an encoding from the value of
- // the charset attribute. If el does not have a charset attribute, or if getting an encoding failed, then
- // let encoding be el's node document's encoding.
- // NB: An SVG script element has no charset attribute.
- auto encoding = document().encoding_or_default();
-
- // 24. Let classic script CORS setting be the current state of el's crossorigin content attribute.
- auto crossorigin = get_attribute(HTML::AttributeNames::crossorigin);
- auto cors_setting = HTML::cors_setting_attribute_from_keyword(crossorigin.map([](auto const& value) { return value.utf16_view(); }));
-
- // 25-31. Let options be a script fetch options for el.
- // NB: An SVG script element has no integrity or fetchpriority attribute.
- auto referrer_policy_attribute = get_attribute(HTML::AttributeNames::referrerpolicy).value_or({});
- auto referrer_policy = ReferrerPolicy::from_string(referrer_policy_attribute).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString);
- HTML::ScriptElementFetchAttributes fetch_attributes {
- .crossorigin = cors_setting,
- .cryptographic_nonce = nonce(),
- .referrer_policy = referrer_policy,
- .parser_inserted = is_parser_inserted(),
- };
- auto options = HTML::script_element_fetch_options(*this, fetch_attributes);
-
- // 32. Let settings object be el's node document's relevant settings object.
- auto& settings_object = document().relevant_settings_object();
-
- // 3. The 'script' element's "already processed" flag is set to true.
- // We set this before dispatching the fetch so that re-entrant calls (e.g. from attribute_changed
- // while the fetch is in flight) early-return at step 1, matching Chromium's `already_started_`
- // semantics. The in-flight fetch is allowed to finish.
- m_already_processed = true;
-
- // https://html.spec.whatwg.org/multipage/scripting.html#prepare-the-script-element
- // 33.8. Set el's delaying the load event to true.
- m_document_load_event_delayer.emplace(*m_preparation_time_document);
-
- // 33.11. Switch on el's type: "classic": Fetch a classic script given url, settings object, options, classic
- // script CORS setting, encoding, and onComplete.
- auto on_complete = HTML::create_on_fetch_script_complete(heap(), [self = GC::Ref { *this }](GC::Ptr<HTML::Script> script) {
- self->finish_external_script_fetch(as<HTML::ClassicScript>(script.ptr()));
- });
- HTML::fetch_classic_script(HTML::relevant_realm(*this), script_url, settings_object, move(options), cors_setting, move(encoding), on_complete);
-
- // 35.5.1. Set el's parser document's pending parsing-blocking script to el.
- if (m_parser_inserted)
- m_document->set_pending_parsing_blocking_svg_script(this);
- return;
- }
-
- auto script_content = child_text_content();
- if (script_content.is_empty()) {
- // AD-HOC: The parser is done with an empty script once it gets here, so a later change to the script's
- // children should process it like for a script that the parser did not insert.
- m_parser_inserted = false;
- return;
- }
-
- // 3. The 'script' element's "already processed" flag is set to true.
- m_already_processed = true;
- m_script = HTML::ClassicScript::create(m_document->url().basename(), script_content,
- HTML::relevant_settings_object(*this), m_document->base_url(), m_source_line_number, HTML::ClassicScript::MutedErrors::No, HTML::ScriptRegistry::IsInlineSource::Yes);
- execute_script();
+ script_element_post_connection();
}
-void SVGScriptElement::finish_external_script_fetch(GC::Ptr<HTML::ClassicScript> script)
+WebIDL::ExceptionOr<void> SVGScriptElement::cloned(Node& copy, bool subtree) const
{
- if (in_a_document_tree() && !is_scripting_disabled())
- m_script = script;
-
- if (m_parser_inserted) {
- // https://html.spec.whatwg.org/multipage/scripting.html#mark-as-ready
- // 4. Set el's delaying the load event to false.
- m_document_load_event_delayer.clear();
-
- // NB: The parser that waits for a parser-inserted script is its preparation-time document's.
- m_ready_to_be_parser_executed = true;
- m_preparation_time_document->schedule_html_parser_end_check();
- return;
- }
+ TRY(Base::cloned(copy, subtree));
+ script_element_cloned(as<SVGScriptElement>(copy));
+ return {};
+}
- ScopeGuard clear_delayer { [&] { m_document_load_event_delayer.clear(); } };
- execute_script();
+bool SVGScriptElement::has_source_attribute() const
+{
+ return has_attribute(SVG::AttributeNames::href) || has_attribute_ns(Namespace::XLink, SVG::AttributeNames::href);
}
-void SVGScriptElement::execute_pending_parser_blocking_script(Badge<HTML::HTMLParser>)
+Utf16String SVGScriptElement::source_attribute_value()
{
- VERIFY(m_ready_to_be_parser_executed);
- m_ready_to_be_parser_executed = false;
- execute_script();
+ return href()->base_val();
}
-void SVGScriptElement::execute_script()
+HTML::ScriptElementFetchAttributes SVGScriptElement::fetch_attributes() const
{
- // 4. If the script content is inline, or if it is external and was fetched successfully, then the
- // script is executed. Note that at this point, these steps may be re-entrant if the execution
- // of the script results in further 'script' elements being inserted into the document.
-
- // https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-element
- // 1. Let document be el's node document.
- // 2. If el's preparation-time document is not equal to document, then return.
- if (m_preparation_time_document.ptr() != &document())
- return;
-
- // m_script is null when the external fetch failed; the parser-blocking slot still needs to be drained
- // so the parser can resume, but there's no script to run.
- if (!m_script)
- return;
-
- // https://html.spec.whatwg.org/multipage/document-lifecycle.html#read-html
- // Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for document.
- if (!m_document->ready_to_run_scripts())
- return;
-
- // FIXME: Note that a load event is dispatched on a 'script' element once it has been processed,
- // unless it referenced external script content with an invalid IRI reference and 'externalResourcesRequired' was set to 'true'.
-
- (void)m_script->run();
+ auto crossorigin = get_attribute(HTML::AttributeNames::crossorigin);
+ auto referrer_policy_attribute = get_attribute(HTML::AttributeNames::referrerpolicy).value_or({});
+ return {
+ .crossorigin = HTML::cors_setting_attribute_from_keyword(crossorigin.map([](auto const& value) { return value.utf16_view(); })),
+ .cryptographic_nonce = nonce(),
+ .referrer_policy = ReferrerPolicy::from_string(referrer_policy_attribute).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString),
+ .parser_inserted = is_parser_inserted(),
+ };
}
}
diff --git a/Libraries/LibWeb/SVG/SVGScriptElement.h b/Libraries/LibWeb/SVG/SVGScriptElement.h
index df9530809c5..241e91876f0 100644
--- a/Libraries/LibWeb/SVG/SVGScriptElement.h
+++ b/Libraries/LibWeb/SVG/SVGScriptElement.h
@@ -6,10 +6,7 @@
#pragma once
-#include <AK/Forward.h>
-#include <LibURL/URL.h>
-#include <LibWeb/DOM/DocumentLoadEventDelayer.h>
-#include <LibWeb/HTML/Scripting/ClassicScript.h>
+#include <LibWeb/HTML/HTMLOrSVGScriptElement.h>
#include <LibWeb/SVG/SVGElement.h>
#include <LibWeb/SVG/SVGURIReference.h>
@@ -18,25 +15,17 @@ namespace Web::SVG {
// https://www.w3.org/TR/SVG/interact.html#InterfaceSVGScriptElement
class SVGScriptElement
: public SVGElement
- , public SVGURIReferenceMixin<SupportsXLinkHref::Yes> {
+ , public SVGURIReferenceMixin<SupportsXLinkHref::Yes>
+ , public HTML::HTMLOrSVGScriptElement {
WEB_WRAPPABLE(SVGScriptElement, SVGElement);
GC_DECLARE_ALLOCATOR(SVGScriptElement);
public:
- void process_the_script_element();
-
- bool is_parser_inserted() const { return m_parser_inserted; }
- void set_parser_inserted(Badge<HTML::HTMLParser>) { m_parser_inserted = true; }
-
- bool is_ready_to_be_parser_executed() const { return m_ready_to_be_parser_executed; }
- void execute_pending_parser_blocking_script(Badge<HTML::HTMLParser>);
- void stop_delaying_document_load_event(Badge<DOM::Document>) { m_document_load_event_delayer.clear(); }
-
- void set_source_line_number(Badge<HTML::HTMLParser>, size_t source_line_number) { m_source_line_number = source_line_number; }
-
- virtual void inserted() override;
virtual void children_changed(ChildrenChangedMetadata const&) override;
+ virtual void post_connection() override;
+ virtual bool has_post_connection_steps() const override { return true; }
virtual void attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_) override;
+ virtual WebIDL::ExceptionOr<void> cloned(Node&, bool) const override;
protected:
SVGScriptElement(DOM::Document&, DOM::QualifiedName);
@@ -47,21 +36,18 @@ private:
virtual void visit_edges(Cell::Visitor&) override;
virtual void adopted_from(DOM::Document&) override;
- void finish_external_script_fetch(GC::Ptr<HTML::ClassicScript>);
- void execute_script();
-
- // https://html.spec.whatwg.org/multipage/scripting.html#preparation-time-document
- GC::Ptr<DOM::Document> m_preparation_time_document;
-
- bool m_already_processed { false };
- bool m_parser_inserted { false };
- bool m_ready_to_be_parser_executed { false };
-
- GC::Ptr<HTML::ClassicScript> m_script;
-
- Optional<DOM::DocumentLoadEventDelayer> m_document_load_event_delayer;
-
- size_t m_source_line_number { 1 };
+ // ^HTMLOrSVGScriptElement
+ virtual DOM::Element& as_element() override { return *this; }
+ virtual DOM::Element const& as_element() const override { return *this; }
+ virtual bool has_source_attribute() const override;
+ virtual Utf16String source_attribute_value() override;
+ virtual Optional<Utf16String> language_attribute_value() const override { return {}; }
+ virtual Optional<Utf16String> charset_attribute_value() const override { return {}; }
+ virtual Optional<Utf16String> event_attribute_value() const override { return {}; }
+ virtual Optional<Utf16String> for_attribute_value() const override { return {}; }
+ virtual bool has_defer_attribute() const override { return false; }
+ virtual bool has_nomodule_attribute() const override { return false; }
+ virtual HTML::ScriptElementFetchAttributes fetch_attributes() const override;
};
}
diff --git a/Libraries/LibWeb/TrustedTypes/InjectionSink.h b/Libraries/LibWeb/TrustedTypes/InjectionSink.h
index 7de3936676a..e3eab9ee9ee 100644
--- a/Libraries/LibWeb/TrustedTypes/InjectionSink.h
+++ b/Libraries/LibWeb/TrustedTypes/InjectionSink.h
@@ -47,6 +47,7 @@ namespace Web::TrustedTypes {
__ENUMERATE_INJECTION_SINKS(ShadowRoot_setHTMLUnsafe, "ShadowRoot setHTMLUnsafe") \
__ENUMERATE_INJECTION_SINKS(SharedWorker_constructor, "SharedWorker constructor") \
__ENUMERATE_INJECTION_SINKS(SVGScriptElement_href, "SVGScriptElement href") \
+ __ENUMERATE_INJECTION_SINKS(SVGScriptElement_text, "SVGScriptElement text") \
__ENUMERATE_INJECTION_SINKS(Window_setInterval, "Window setInterval") \
__ENUMERATE_INJECTION_SINKS(Window_setTimeout, "Window setTimeout") \
__ENUMERATE_INJECTION_SINKS(Worker_constructor, "Worker constructor") \
diff --git a/Libraries/LibWeb/XML/XMLDocumentBuilder.cpp b/Libraries/LibWeb/XML/XMLDocumentBuilder.cpp
index 94b8270a2fd..35e43b1403d 100644
--- a/Libraries/LibWeb/XML/XMLDocumentBuilder.cpp
+++ b/Libraries/LibWeb/XML/XMLDocumentBuilder.cpp
@@ -16,7 +16,6 @@
#include <LibWeb/HTML/Parser/Entities.h>
#include <LibWeb/HTML/Parser/NamedCharacterReferences.h>
#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/SVG/SVGScriptElement.h>
#include <LibWeb/SVG/TagNames.h>
#include <LibWeb/XML/XMLDocumentBuilder.h>
@@ -137,10 +136,10 @@ void XMLDocumentBuilder::element_start(Utf16FlyString const& name, Vector<XML::L
// When an XML parser with XML scripting support enabled creates a script element,
// it must have its parser document set and its "force async" flag must be unset.
// FIXME: If the parser was created as part of the XML fragment parsing algorithm, then the element must be marked as "already started" also.
- if (m_scripting_support == XMLScriptingSupport::Enabled && node->is_html_script_element()) {
- auto& script_element = static_cast<HTML::HTMLScriptElement&>(*node);
- script_element.set_parser_document(Badge<XMLDocumentBuilder> {}, m_document);
- script_element.set_force_async(Badge<XMLDocumentBuilder> {}, false);
+ // AD-HOC: SVG script elements are processed like HTML script elements, since SVG defines them as equivalent.
+ if (auto* script_element = as_if<HTML::HTMLOrSVGScriptElement>(*node); script_element && m_scripting_support == XMLScriptingSupport::Enabled) {
+ script_element->set_parser_document(Badge<XMLDocumentBuilder> {}, m_document);
+ script_element->set_force_async(Badge<XMLDocumentBuilder> {}, false);
}
// AD-HOC: Let <link> elements know which document they were originally parsed for.
@@ -204,14 +203,13 @@ void XMLDocumentBuilder::element_end(Utf16FlyString const& name)
VERIFY(m_current_node->node_name().equals_ignoring_ascii_case(name));
// When an XML parser with XML scripting support enabled creates a script element, [...]
// When the element's end tag is subsequently parsed,
- if (m_scripting_support == XMLScriptingSupport::Enabled && m_current_node->is_html_script_element()) {
+ if (auto* script_element = as_if<HTML::HTMLOrSVGScriptElement>(*m_current_node); script_element && m_scripting_support == XMLScriptingSupport::Enabled) {
// the user agent must perform a microtask checkpoint,
HTML::perform_a_microtask_checkpoint();
// and then prepare the script element.
- auto& script_element = static_cast<HTML::HTMLScriptElement&>(*m_current_node);
// AD-HOC: Set the script text value for Trusted Types as the HTML parser does, matching other engines.
- script_element.set_script_text_from_parser();
- script_element.prepare_script(Badge<XMLDocumentBuilder> {});
+ script_element->set_script_text_from_parser();
+ script_element->prepare_script(Badge<XMLDocumentBuilder> {});
// If this causes there to be a pending parsing-blocking script, then the user agent must run the following steps:
if (auto pending_parsing_blocking_script = m_document->pending_parsing_blocking_script()) {
@@ -234,14 +232,7 @@ void XMLDocumentBuilder::element_end(Utf16FlyString const& name)
// 5. Set the pending parsing-blocking script to null.
m_document->set_pending_parsing_blocking_script(nullptr);
}
- } else if (m_scripting_support == XMLScriptingSupport::Enabled && m_current_node->is_svg_script_element()) {
- // https://www.w3.org/TR/SVGMobile12/struct.html#ProgressiveRendering
- // When an end element event occurs for a 'script' element, that element is processed according to the
- // Script processing section of the Scripting chapter. Further parsing of the document will be blocked
- // until processing of the 'script' is complete.
- auto& script_element = static_cast<SVG::SVGScriptElement&>(*m_current_node);
- script_element.process_the_script_element();
- };
+ }
(void)m_open_elements.take_last();
if (m_open_elements.is_empty()) {
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 40b0a4c24df..ff17bd6b0fe 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -77,6 +77,7 @@ Text/input/wpt-import/cookies/attributes/domain.sub.html
; Import modules by URL, which needs an HTTP origin.
Text/input/wpt-import/trusted-types/script-enforcement-006.html
+Text/input/wpt-import/trusted-types/script-enforcement-007.html
Text/input/wpt-import/html/semantics/scripting-1/the-script-element/module/dynamic-import/propagate-nonce-external-classic.html
Text/input/wpt-import/html/semantics/scripting-1/the-script-element/module/dynamic-import/propagate-nonce-external-module.html
Text/input/wpt-import/html/semantics/scripting-1/the-script-element/module/dynamic-import/propagate-nonce-inline-classic.html
diff --git a/Tests/LibWeb/Text/expected/ContentSecurityPolicy/svg-inline-script.txt b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/svg-inline-script.txt
new file mode 100644
index 00000000000..7660655eb8c
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/ContentSecurityPolicy/svg-inline-script.txt
@@ -0,0 +1,3 @@
+PASS: inline SVG script with a nonce executed
+PASS: inline SVG script without a nonce blocked
+PASS: inserted SVG script without a nonce blocked
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-document-external-script-blocks-parser.txt b/Tests/LibWeb/Text/expected/SVG/svg-document-external-script-blocks-parser.txt
new file mode 100644
index 00000000000..fe6cd1aefba
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-document-external-script-blocks-parser.txt
@@ -0,0 +1 @@
+External script of an SVG document before the following script: ran
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-script-async.txt b/Tests/LibWeb/Text/expected/SVG/svg-script-async.txt
new file mode 100644
index 00000000000..2cfde779540
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-script-async.txt
@@ -0,0 +1,2 @@
+Async SVG script ran before the following script: false
+Async SVG script ran before the load event: true
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-script-current-script.txt b/Tests/LibWeb/Text/expected/SVG/svg-script-current-script.txt
new file mode 100644
index 00000000000..e3b413d0f35
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-script-current-script.txt
@@ -0,0 +1 @@
+document.currentScript while an SVG script runs is that script: true
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-script-load-and-error-events.txt b/Tests/LibWeb/Text/expected/SVG/svg-script-load-and-error-events.txt
new file mode 100644
index 00000000000..4be1f5f00db
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-script-load-and-error-events.txt
@@ -0,0 +1,2 @@
+SVG script with a script URL fired: load
+SVG script with an empty href fired: error
diff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden-meta.sub.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden-meta.sub.txt
new file mode 100644
index 00000000000..c29c18854c5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden-meta.sub.txt
@@ -0,0 +1,14 @@
+Harness status: OK
+
+Found 9 tests
+
+9 Pass
+Pass Reading 'nonce' content attribute and IDL attribute.
+Pass Cloned node retains nonce.
+Pass Cloned node retains nonce when inserted.
+Pass Writing 'nonce' content attribute.
+Pass Writing 'nonce' IDL attribute.
+Pass Document-written script executes.
+Pass Document-written script's nonce value.
+Pass createElement.nonce.
+Pass createElement.setAttribute.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden.txt b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden.txt
new file mode 100644
index 00000000000..c29c18854c5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden.txt
@@ -0,0 +1,14 @@
+Harness status: OK
+
+Found 9 tests
+
+9 Pass
+Pass Reading 'nonce' content attribute and IDL attribute.
+Pass Cloned node retains nonce.
+Pass Cloned node retains nonce when inserted.
+Pass Writing 'nonce' content attribute.
+Pass Writing 'nonce' IDL attribute.
+Pass Document-written script executes.
+Pass Document-written script's nonce value.
+Pass createElement.nonce.
+Pass createElement.setAttribute.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/html/semantics/scripting-1/the-script-element/svg-script-fragment-parsed-not-executed-on-clone.txt b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/scripting-1/the-script-element/svg-script-fragment-parsed-not-executed-on-clone.txt
new file mode 100644
index 00000000000..cad10def233
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/html/semantics/scripting-1/the-script-element/svg-script-fragment-parsed-not-executed-on-clone.txt
@@ -0,0 +1,9 @@
+Harness status: OK
+
+Found 4 tests
+
+4 Pass
+Pass Sanity check: a normally-created SVG <script> runs when inserted
+Pass A fragment-parsed SVG <script> does not execute when cloned into the document
+Pass Deep-cloning a subtree containing a fragment-parsed SVG <script> does not execute it
+Pass Control: a fragment-parsed HTML <script> does not execute when cloned into the document
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/svg/scripted/script-runs-in-shadow-tree.txt b/Tests/LibWeb/Text/expected/wpt-import/svg/scripted/script-runs-in-shadow-tree.txt
new file mode 100644
index 00000000000..7efd2b5d7cd
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/svg/scripted/script-runs-in-shadow-tree.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass svg:script runs correctly in a shadow tree
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/svg/struct/scripted/use-script-not-executed.txt b/Tests/LibWeb/Text/expected/wpt-import/svg/struct/scripted/use-script-not-executed.txt
index 2bab06d6299..bab8566c860 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/svg/struct/scripted/use-script-not-executed.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/svg/struct/scripted/use-script-not-executed.txt
@@ -2,9 +2,8 @@ Harness status: OK
Found 6 tests
-5 Pass
-1 Fail
-Fail Not-yet-started svg-script cloned by a use element doesn't run
+6 Pass
+Pass Not-yet-started svg-script cloned by a use element doesn't run
Pass Not-yet-started html-script cloned by a use element doesn't run
Pass Not-yet-started shadow-script cloned by a use element doesn't run
Pass Not-yet-started root-html-script cloned by a use element doesn't run
diff --git a/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-003.txt b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-003.txt
new file mode 100644
index 00000000000..db2f1b6e04a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-003.txt
@@ -0,0 +1,38 @@
+Harness status: OK
+
+Found 33 tests
+
+33 Pass
+Pass The SVGScriptElement is initially trusted.
+Pass Script source set via Element.textContent drops trustworthiness.
+Pass Script source set via Node.textContent drops trustworthiness.
+Pass Script source set via TrustedHTML sink Element.innerHTML drops trustworthiness.
+Pass Script source set via TrustedHTML sink Element.outerHTML drops trustworthiness.
+Pass Script source set via TrustedHTML sink Element.setHTMLUnsafe() drops trustworthiness.
+Pass Script source cannot be set via Element.setHTML().
+Pass Splitting script source via Text.splitText() keeps trustworthiness.
+Pass Normalizing script source via Element.normalize() keeps trustworthiness.
+Pass Script source set via Node.nodeValue drops trustworthiness.
+Pass Setting script source via CharacterData.data drops trustworthiness.
+Pass Setting script source via CharacterData.appendData() drops trustworthiness.
+Pass Setting script source via CharacterData.insertData() drops trustworthiness.
+Pass Setting script source via CharacterData.replaceData() drops trustworthiness.
+Pass Setting script source via CharacterData.deleteData() drops trustworthiness.
+Pass Setting script source via CharacterData.before() drops trustworthiness.
+Pass Setting script source via CharacterData.after() drops trustworthiness.
+Pass Setting script source via CharacterData.remove() drops trustworthiness.
+Pass Setting script source via CharacterData.replaceWith() drops trustworthiness.
+Pass Setting script source via Node.appendChild() drops trustworthiness.
+Pass Setting script source via Node.insertBefore() drops trustworthiness.
+Pass Setting script source via Node.replaceChild() drops trustworthiness.
+Pass Setting script source via Node.removeChild() drops trustworthiness.
+Pass Setting script source via Element.prepend() drops trustworthiness.
+Pass Setting script source via Element.append() drops trustworthiness.
+Pass Setting script source via Element.replaceChildren() drops trustworthiness.
+Pass Setting script source via Element.moveBefore() drops trustworthiness.
+Pass Setting script source via TrustedHTML sink Node.insertAdjacentHTML() drops trustworthiness.
+Pass Setting script source via Node.insertAdjacentText() drops trustworthiness.
+Pass Setting script source via Range.insertNode() drops trustworthiness.
+Pass Setting script source via Range.deleteContents() drops trustworthiness.
+Pass Cloning a script via Node.cloneNode() drops trustworthiness.
+Pass Cloning a script via Range.cloneContents() drops trustworthiness.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-004.txt b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-004.txt
new file mode 100644
index 00000000000..5051cb22ac4
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-004.txt
@@ -0,0 +1,36 @@
+Harness status: OK
+
+Found 31 tests
+
+31 Pass
+Pass Default policy's calls when setting script source via SVGScriptElement.textContent.
+Pass Verify when the default policy is called for script set source via Node.textContent.
+Pass Default policy's calls when setting script source via Element.innerHTML.
+Pass Default policy's calls when setting script source via Element.outerHTML.
+Pass Default policy's calls when setting script source via Element.setHTMLUnsafe().
+Pass Default policy when splitting script source via Text.splitText().
+Pass Default policy when normalizing script source via Element.normalize().
+Pass Default policy's calls when setting script source via Node.nodeValue.
+Pass Default policy's calls when setting script source via CharacterData.data.
+Pass Default policy's calls when setting script source via CharacterData.appendData().
+Pass Default policy's calls when setting script source via CharacterData.insertData().
+Pass Default policy's calls when setting script source via CharacterData.replaceData().
+Pass Default policy's calls when setting script source via CharacterData.deleteData().
+Pass Default policy's calls when setting script source via CharacterData.before().
+Pass Default policy's calls when setting script source via CharacterData.after().
+Pass Default policy's calls when setting script source via CharacterData.remove().
+Pass Default policy's calls when setting script source via CharacterData.replaceWith().
+Pass Default policy's calls when setting script source via Node.appendChild().
+Pass Default policy's calls when setting script source via Node.insertBefore().
+Pass Default policy's calls when setting script source via Node.replaceChild().
+Pass Default policy's calls when setting script source via Node.removeChild().
+Pass Default policy's calls when setting script source via Element.prepend().
+Pass Default policy's calls when setting script source via Element.append().
+Pass Default policy's calls when setting script source via Element.replaceChildren().
+Pass Default policy's calls when setting script source via Element.moveBefore().
+Pass Default policy's calls when setting script source via Node.insertAdjacentText().
+Pass Default policy's calls when setting script source via Node.insertAdjacentHTML().
+Pass Default policy's calls when setting source via Range.insertNode().
+Pass Default policy's calls when setting script source via Range.deleteContents().
+Pass Default policy's calls when cloning a script via Node.cloneNode().
+Pass Default policy's calls when cloning a script via Range.cloneContents().
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-005.txt b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-005.txt
index dc2424a6a2b..9a2958b4402 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-005.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-005.txt
@@ -2,9 +2,8 @@ Harness status: OK
Found 4 tests
-2 Pass
-2 Fail
+4 Pass
Pass Empty HTMLScriptElement is executed if the default policy makes it non-empty.
Pass Non-empty HTMLScriptElement is not executed if the default policy makes it empty.
-Fail Empty SVGScriptElement is executed if the default policy makes it non-empty.
-Fail Non-empty SVGScriptElement is not executed if the default policy makes it empty.
\ No newline at end of file
+Pass Empty SVGScriptElement is executed if the default policy makes it non-empty.
+Pass Non-empty SVGScriptElement is not executed if the default policy makes it empty.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-007.txt b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-007.txt
new file mode 100644
index 00000000000..8f1f1e08b81
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-007.txt
@@ -0,0 +1,10 @@
+Harness status: OK
+
+Found 4 tests
+
+3 Pass
+1 Fail
+Pass Untrusted SVGScriptElement with classic type uses the source text returned by the default policy.
+Pass Untrusted SVGScriptElement of importmap type uses the source text returned by the default policy.
+Pass Untrusted SVGScriptElement of module type uses the source text returned by the default policy.
+Fail Untrusted SVGScriptElement of two importmap type use the source text returned by the default policy.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-011.txt b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-011.txt
new file mode 100644
index 00000000000..fa1a6b450c5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/trusted-types/script-enforcement-011.txt
@@ -0,0 +1,7 @@
+Harness status: OK
+
+Found 2 tests
+
+2 Pass
+Pass Changing script's type from classic to module in the default policy works.
+Pass Changing script's type from module to classic in the default policy works.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/xhr/responseXML-xml-scripting-support-disabled.txt b/Tests/LibWeb/Text/expected/wpt-import/xhr/responseXML-xml-scripting-support-disabled.txt
index 75367529756..4b5d5e2073d 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/xhr/responseXML-xml-scripting-support-disabled.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/xhr/responseXML-xml-scripting-support-disabled.txt
@@ -2,10 +2,9 @@ Harness status: OK
Found 5 tests
-2 Pass
-3 Fail
-Fail XMLHttpRequest responseXML, svg script, appendChild
-Fail XMLHttpRequest responseXML, svg script, append importNode result
-Fail XMLHttpRequest responseXML, svg script, append adoptNode result
+5 Pass
+Pass XMLHttpRequest responseXML, svg script, appendChild
+Pass XMLHttpRequest responseXML, svg script, append importNode result
+Pass XMLHttpRequest responseXML, svg script, append adoptNode result
Pass XMLHttpRequest responseXML, xhtml script, append importNode result
Pass XMLHttpRequest responseXML, xhtml script, append adoptNode result
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/ContentSecurityPolicy/svg-inline-script.html b/Tests/LibWeb/Text/input/ContentSecurityPolicy/svg-inline-script.html
new file mode 100644
index 00000000000..63464149ea2
--- /dev/null
+++ b/Tests/LibWeb/Text/input/ContentSecurityPolicy/svg-inline-script.html
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<meta http-equiv="Content-Security-Policy" content="script-src 'nonce-good'">
+<svg><script nonce=good>globalThis.noncedSVGScriptExecuted = true;</script></svg>
+<svg><script>globalThis.svgScriptWithoutNonceExecuted = true;</script></svg>
+<script nonce=good>
+ const script = document.createElementNS("http://www.w3.org/2000/svg", "script");
+ script.textContent = "globalThis.insertedSVGScriptWithoutNonceExecuted = true;";
+ document.querySelector("svg").appendChild(script);
+
+ test(() => {
+ println(globalThis.noncedSVGScriptExecuted ? "PASS: inline SVG script with a nonce executed" : "FAIL: inline SVG script with a nonce blocked");
+ println(globalThis.svgScriptWithoutNonceExecuted ? "FAIL: inline SVG script without a nonce executed" : "PASS: inline SVG script without a nonce blocked");
+ println(globalThis.insertedSVGScriptWithoutNonceExecuted ? "FAIL: inserted SVG script without a nonce executed" : "PASS: inserted SVG script without a nonce blocked");
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-document-external-script-blocks-parser.html b/Tests/LibWeb/Text/input/SVG/svg-document-external-script-blocks-parser.html
new file mode 100644
index 00000000000..1ffca186a8d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-document-external-script-blocks-parser.html
@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const server = httpTestServer();
+ const scriptURL = await server.createEcho("GET", "/svg-document-external-script-blocks-parser.js", {
+ status: 200,
+ headers: { "Content-Type": "text/javascript" },
+ body: "globalThis.externalScriptExecuted = true;",
+ });
+ const scriptStartTag = "<scr" + "ipt";
+ const scriptEndTag = "</scr" + "ipt>";
+ const documentURL = await server.createEcho("GET", "/svg-document-external-script-blocks-parser.svg", {
+ status: 200,
+ headers: { "Content-Type": "image/svg+xml" },
+ body: `<svg xmlns="http://www.w3.org/2000/svg">
+ ${scriptStartTag} href="${scriptURL}">${scriptEndTag}
+ ${scriptStartTag}>parent.postMessage(globalThis.externalScriptExecuted ? "ran" : "had not run", "*");${scriptEndTag}
+ </svg>`,
+ });
+
+ window.addEventListener(
+ "message",
+ event => {
+ println(`External script of an SVG document before the following script: ${event.data}`);
+ done();
+ },
+ { once: true }
+ );
+
+ const frame = document.createElement("iframe");
+ frame.src = documentURL;
+ document.body.appendChild(frame);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-async.html b/Tests/LibWeb/Text/input/SVG/svg-script-async.html
new file mode 100644
index 00000000000..99a9652629b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-async.html
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<svg><script async href="data:text/javascript,globalThis.asyncSVGScriptExecuted = true;"></script></svg>
+<script>
+ const executedBeforeFollowingScript = !!globalThis.asyncSVGScriptExecuted;
+
+ asyncTest(done => {
+ window.addEventListener("load", () => {
+ println(`Async SVG script ran before the following script: ${executedBeforeFollowingScript}`);
+ println(`Async SVG script ran before the load event: ${!!globalThis.asyncSVGScriptExecuted}`);
+ done();
+ });
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-current-script.html b/Tests/LibWeb/Text/input/SVG/svg-script-current-script.html
new file mode 100644
index 00000000000..5f742f42da1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-current-script.html
@@ -0,0 +1,8 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<svg><script id="svg-script">globalThis.currentScriptDuringSVGScript = document.currentScript;</script></svg>
+<script>
+ test(() => {
+ println(`document.currentScript while an SVG script runs is that script: ${globalThis.currentScriptDuringSVGScript === document.getElementById("svg-script")}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-script-load-and-error-events.html b/Tests/LibWeb/Text/input/SVG/svg-script-load-and-error-events.html
new file mode 100644
index 00000000000..38b92213e58
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-script-load-and-error-events.html
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<svg></svg>
+<script>
+ function insertSVGScript(href) {
+ return new Promise(resolve => {
+ const script = document.createElementNS("http://www.w3.org/2000/svg", "script");
+ script.setAttribute("href", href);
+ script.addEventListener("load", () => resolve("load"));
+ script.addEventListener("error", () => resolve("error"));
+ document.querySelector("svg").appendChild(script);
+ });
+ }
+
+ promiseTest(async () => {
+ println(`SVG script with a script URL fired: ${await insertSVGScript("data:text/javascript,")}`);
+ println(`SVG script with an empty href fired: ${await insertSVGScript("")}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden-meta.sub.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden-meta.sub.html
new file mode 100644
index 00000000000..bbb308e91c1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden-meta.sub.html
@@ -0,0 +1,100 @@
+<!DOCTYPE html>
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+
+<meta http-equiv="content-security-policy" content="script-src 'nonce-abc'; img-src 'none'">
+
+<body>
+<!-- Basics -->
+<svg xmlns="http://www.w3.org/2000/svg">
+ <script nonce="abc" id="testScript">
+ document.currentScript.setAttribute('executed', 'yay');
+ </script>
+</svg>
+
+<script nonce="abc">
+ var script = document.querySelector('#testScript');
+
+ test(t => {
+ // Query Selector
+ assert_equals(document.querySelector('[nonce]'), script);
+ assert_equals(document.querySelector('[nonce=""]'), null);
+ assert_equals(document.querySelector('[nonce=abc]'), script);
+
+ assert_equals(script.getAttribute('nonce'), 'abc');
+ assert_equals(script.nonce, 'abc');
+ }, "Reading 'nonce' content attribute and IDL attribute.");
+
+ // Clone node.
+ test(t => {
+ script.setAttribute('executed', 'boo');
+ var s2 = script.cloneNode();
+ assert_equals(s2.nonce, 'abc', 'IDL attribute');
+ assert_equals(s2.getAttribute('nonce'), 'abc');
+ }, "Cloned node retains nonce.");
+
+ async_test(t => {
+ var s2 = script.cloneNode();
+ document.head.appendChild(s2);
+ assert_equals(s2.nonce, 'abc');
+ assert_equals(s2.getAttribute('nonce'), 'abc');
+
+ window.addEventListener('load', t.step_func_done(_ => {
+ // The cloned script won't execute, as its 'already started' flag is set.
+ assert_equals(s2.getAttribute('executed'), 'boo');
+ }));
+ }, "Cloned node retains nonce when inserted.");
+
+ // Set the content attribute to 'foo'
+ test(t => {
+ script.setAttribute('nonce', 'foo');
+ assert_equals(script.getAttribute('nonce'), 'foo');
+ assert_equals(script.nonce, 'foo');
+ }, "Writing 'nonce' content attribute.");
+
+ // Set the IDL attribute to 'bar'
+ test(t => {
+ script.nonce = 'bar';
+ assert_equals(script.nonce, 'bar');
+ assert_equals(script.getAttribute('nonce'), 'foo');
+ }, "Writing 'nonce' IDL attribute.");
+
+ // Fragment parser.
+ var documentWriteTest = async_test("Document-written script executes.");
+ document.write(`<svg xmlns="http://www.w3.org/2000/svg"><script nonce='abc'>
+ documentWriteTest.done();
+ test(t => {
+ var script = document.currentScript;
+ assert_equals(script.getAttribute('nonce'), 'abc');
+ assert_equals(script.nonce, 'abc');
+ }, "Document-written script's nonce value.");
+ </scr` + `ipt></svg>`);
+
+ // Create node.
+ test(t => {
+ var s = document.createElement('svg');
+ var innerScript = document.createElement('innerScript');
+ innerScript.innerText = script.innerText;
+ innerScript.nonce = 'abc';
+ s.appendChild(innerScript);
+ assert_equals(innerScript.nonce, 'abc');
+ assert_equals(innerScript.getAttribute('nonce'), null, 'innerScript.getAttribute nonce');
+ document.body.appendChild(s);
+ assert_equals(innerScript.nonce, 'abc');
+ assert_equals(innerScript.getAttribute('nonce'), null, 'innerScript.getAttribute nonce');
+ }, "createElement.nonce.");
+
+ // Create node.
+ test(t => {
+ var s = document.createElement('svg');
+ var innerScript = document.createElement('script');
+ innerScript.innerText = script.innerText;
+ innerScript.setAttribute('nonce', 'abc');
+ assert_equals(innerScript.getAttribute('nonce'), 'abc', "Pre-insertion content");
+ assert_equals(innerScript.nonce, 'abc', "Pre-insertion IDL");
+ s.appendChild(innerScript);
+ document.body.appendChild(s);
+ assert_equals(innerScript.nonce, 'abc', "Post-insertion IDL");
+ assert_equals(innerScript.getAttribute('nonce'), 'abc', "Post-insertion content");
+ }, "createElement.setAttribute.");
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden.html b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden.html
new file mode 100644
index 00000000000..dd0724a349c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden.html
@@ -0,0 +1,98 @@
+<!DOCTYPE html>
+<script src="../../resources/testharness.js" nonce="abc"></script>
+<script src="../../resources/testharnessreport.js" nonce="abc"></script>
+
+<!-- `Content-Security-Policy: script-src 'nonce-abc'; img-src 'none'` delivered via headers -->
+
+<body>
+<!-- Basics -->
+<svg xmlns="http://www.w3.org/2000/svg">
+ <script nonce="abc" id="testScript">
+ document.currentScript.setAttribute('executed', 'yay');
+ </script>
+</svg>
+
+<script nonce="abc">
+ var script = document.querySelector('#testScript');
+
+ test(t => {
+ // Query Selector
+ assert_equals(document.querySelector('body [nonce]'), script);
+ assert_equals(document.querySelector('body [nonce=""]'), script);
+ assert_equals(document.querySelector('body [nonce=abc]'), null);
+
+ assert_equals(script.getAttribute('nonce'), '');
+ assert_equals(script.nonce, 'abc');
+ }, "Reading 'nonce' content attribute and IDL attribute.");
+
+ // Clone node.
+ test(t => {
+ script.setAttribute('executed', 'boo');
+ var s2 = script.cloneNode();
+ assert_equals(s2.nonce, 'abc', 'IDL attribute');
+ assert_equals(s2.getAttribute('nonce'), '');
+ }, "Cloned node retains nonce.");
+
+ async_test(t => {
+ var s2 = script.cloneNode();
+ document.head.appendChild(s2);
+ assert_equals(s2.nonce, 'abc');
+ assert_equals(s2.getAttribute('nonce'), '');
+
+ window.addEventListener('load', t.step_func_done(_ => {
+ // The cloned script won't execute, as its 'already started' flag is set.
+ assert_equals(s2.getAttribute('executed'), 'boo');
+ }));
+ }, "Cloned node retains nonce when inserted.");
+
+ // Set the content attribute to 'foo'
+ test(t => {
+ script.setAttribute('nonce', 'foo');
+ assert_equals(script.getAttribute('nonce'), 'foo');
+ assert_equals(script.nonce, 'foo');
+ }, "Writing 'nonce' content attribute.");
+
+ // Set the IDL attribute to 'bar'
+ test(t => {
+ script.nonce = 'bar';
+ assert_equals(script.nonce, 'bar');
+ assert_equals(script.getAttribute('nonce'), 'foo');
+ }, "Writing 'nonce' IDL attribute.");
+
+ // Fragment parser.
+ var documentWriteTest = async_test("Document-written script executes.");
+ document.write(`<svg xmlns="http://www.w3.org/2000/svg"><script nonce='abc'>
+ documentWriteTest.done();
+ test(t => {
+ var script = document.currentScript;
+ assert_equals(script.getAttribute('nonce'), '');
+ assert_equals(script.nonce, 'abc');
+ }, "Document-written script's nonce value.");
+ </scr` + `ipt></svg>`);
+
+ // Create node.
+ test(t => {
+ var s = document.createElement('svg');
+ var innerScript = document.createElement('script');
+ innerScript.innerText = script.innerText;
+ innerScript.nonce = 'abc';
+ s.appendChild(innerScript);
+ document.body.appendChild(s);
+ assert_equals(innerScript.nonce, 'abc');
+ assert_equals(innerScript.getAttribute('nonce'), null);
+ }, "createElement.nonce.");
+
+ // Create node.
+ test(t => {
+ var s = document.createElement('svg');
+ var innerScript = document.createElement('script');
+ innerScript.innerText = script.innerText;
+ innerScript.setAttribute('nonce', 'abc');
+ assert_equals(innerScript.getAttribute('nonce'), 'abc', "Pre-insertion content");
+ assert_equals(innerScript.nonce, 'abc', "Pre-insertion IDL");
+ s.appendChild(innerScript);
+ document.body.appendChild(s);
+ assert_equals(innerScript.nonce, 'abc', "Post-insertion IDL");
+ assert_equals(innerScript.getAttribute('nonce'), '', "Post-insertion content");
+ }, "createElement.setAttribute.");
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden.html.headers b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden.html.headers
new file mode 100644
index 00000000000..ad8d0b54f31
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/content-security-policy/nonce-hiding/svgscript-nonces-hidden.html.headers
@@ -0,0 +1 @@
+Content-Security-Policy: script-src 'nonce-abc'; img-src 'none'
diff --git a/Tests/LibWeb/Text/input/wpt-import/html/semantics/scripting-1/the-script-element/svg-script-fragment-parsed-not-executed-on-clone.html b/Tests/LibWeb/Text/input/wpt-import/html/semantics/scripting-1/the-script-element/svg-script-fragment-parsed-not-executed-on-clone.html
new file mode 100644
index 00000000000..5d97f74f8e7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/html/semantics/scripting-1/the-script-element/svg-script-fragment-parsed-not-executed-on-clone.html
@@ -0,0 +1,90 @@
+<!DOCTYPE html>
+<meta charset="utf-8">
+<title>Fragment-parsed SVG script elements are "already started" and do not run when cloned</title>
+<link rel="help" href="https://html.spec.whatwg.org/multipage/parsing.html#create-an-element-for-the-token">
+<link rel="help" href="https://html.spec.whatwg.org/multipage/scripting.html#already-started">
+<link rel="help" href="https://dom.spec.whatwg.org/#concept-node-clone">
+
+<script src="../../../../resources/testharness.js"></script>
+<script src="../../../../resources/testharnessreport.js"></script>
+
+<body>
+<script>
+"use strict";
+
+// A <script> parsed via the fragment parsing algorithm (e.g. innerHTML) is
+// "already started" and never runs, even if later cloned into a document.
+// The same is expected for an SVG <script> in foreign content.
+function makeContainerFromInnerHTML(markup) {
+ const container = document.createElement("div");
+ container.innerHTML = markup;
+ return container;
+}
+
+test(() => {
+ window.svgRan = undefined;
+ const svgNS = "http://www.w3.org/2000/svg";
+ const script = document.createElementNS(svgNS, "script");
+ script.textContent = "window.svgRan = true;";
+ const svg = document.createElementNS(svgNS, "svg");
+ svg.appendChild(script);
+ document.body.appendChild(svg);
+
+ assert_true(window.svgRan,
+ "A normally-created, connected SVG script should run");
+}, "Sanity check: a normally-created SVG <script> runs when inserted");
+
+test(() => {
+ window.svgClonePrimitive = undefined;
+ const container = makeContainerFromInnerHTML(
+ '<svg><script>window.svgClonePrimitive = true;<\/script></svg>');
+
+ assert_equals(window.svgClonePrimitive, undefined,
+ "SVG script must not run when inserted via innerHTML");
+
+ const svgScript = container.querySelector("script");
+ assert_true(!!svgScript, "SVG script element should exist in the fragment");
+
+ // Deep-clone the SVG script and insert it into the connected document.
+ const clone = svgScript.cloneNode(true);
+ document.body.appendChild(clone);
+
+ assert_equals(window.svgClonePrimitive, undefined,
+ "Cloned fragment-parsed SVG script must not execute when inserted");
+}, "A fragment-parsed SVG <script> does not execute when cloned into the document");
+
+test(() => {
+ window.svgCloneNested = undefined;
+ // Nested SVG <script> inside richer innerHTML markup, then deep-cloned.
+ const container = makeContainerFromInnerHTML(
+ '<span class="label">' +
+ '<svg><script>window.svgCloneNested = true;<\/script></svg>' +
+ ' Category</span>');
+
+ assert_equals(window.svgCloneNested, undefined,
+ "Nested SVG script must not run when inserted via innerHTML");
+
+ const clone = container.firstElementChild.cloneNode(true);
+ document.body.appendChild(clone);
+
+ assert_equals(window.svgCloneNested, undefined,
+ "Deep-cloned subtree containing a fragment-parsed SVG script must not execute");
+}, "Deep-cloning a subtree containing a fragment-parsed SVG <script> does not execute it");
+
+test(() => {
+ window.htmlCloneControl = undefined;
+ const container = makeContainerFromInnerHTML(
+ '<script>window.htmlCloneControl = true;<\/script>');
+
+ assert_equals(window.htmlCloneControl, undefined,
+ "HTML script must not run when inserted via innerHTML");
+
+ const htmlScript = container.querySelector("script");
+ const clone = htmlScript.cloneNode(true);
+ document.body.appendChild(clone);
+
+ assert_equals(window.htmlCloneControl, undefined,
+ "Cloned fragment-parsed HTML script must not execute when inserted");
+}, "Control: a fragment-parsed HTML <script> does not execute when cloned into the document");
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/svg/scripted/script-runs-in-shadow-tree.html b/Tests/LibWeb/Text/input/wpt-import/svg/scripted/script-runs-in-shadow-tree.html
new file mode 100644
index 00000000000..ccb6ec4c05c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/svg/scripted/script-runs-in-shadow-tree.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<link rel="author" href="mailto:[email protected]" title="Emilio Cobos Álvarez">
+<link rel="author" href="https://mozilla.org" title="Mozilla">
+<link rel="help" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1555949">
+<script src="../../resources/testharness.js"></script>
+<script src="../../resources/testharnessreport.js"></script>
+<div id="host"></div>
+<script>
+ let svgScript = document.createElementNS("http://www.w3.org/2000/svg", "script");
+ svgScript.innerHTML = "window.scriptRan = true";
+ document.getElementById("host").attachShadow({ mode: "open" }).appendChild(svgScript);
+ test(function() {
+ assert_true(window.scriptRan);
+ }, "svg:script runs correctly in a shadow tree");
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-003.html b/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-003.html
new file mode 100644
index 00000000000..c2e1e6d97a6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-003.html
@@ -0,0 +1,369 @@
+<!DOCTYPE html>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/namespaces.js"></script>
+<script src="support/passthroughpolicy.js"></script>
+<script src="support/script-messages.js"></script>
+<link rel="help" href="https://w3c.github.io/trusted-types/dist/spec/#enforcement-in-scripts">
+<link rel="help" href="https://github.com/w3c/trusted-types/issues/512">
+<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script';">
+<!-- This test is similar to script-enforcement-001 but for the
+ SVGScriptElement, which has slightly different behavior:
+ - No equivalent to HTMLElement.innerText.
+ - No equivalent to HTMLScriptElement.text.
+ - innerHTML and textContent are not Trusted sinks.
+ - The HTML parser can insert elements inside the <script> tag.
+ -->
+<svg>
+ <!-- Provide some static SVGScriptElements for use by
+ document.createElementNS(NSURI_SVG, "script"). See explanation in script-messages.js. -->
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">//;;;window.log_message("RUN")</script>
+ <script type="unknown">//;;;window.log_message("RUN")</script>
+ <script type="unknown">//window.log_message("RUN")</script>
+ <script type="unknown">;;;window.log_message("RUN")/////</script>
+ <script type="unknown">;;;window.log_message("RUN")</script>
+ <script type="unknown">;;;window.log_message("RUN")</script>
+ <script type="unknown">;;;window.log_message("RUN")</script>
+ <script type="unknown">window.log_message("RUN");;;</script>
+ <script type="unknown">window.log_message("RUN");;;</script>
+ <script type="unknown">window.log_message("RUN")</script>
+ <script type="unknown">window.log_message("RUN")</script>
+ <script type="unknown">window.log_message("RUN")</script>
+</svg>
+<svg>
+ <script id="scriptForOuterHTMLTest" type="unknown"><g></g></script>
+</svg>
+<svg id="container"></svg>
+<script>
+ promise_test(async t => {
+ let message = await script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(LOG_RUN_MESSAGE);
+ container.appendChild(script);
+ });
+ assert_equals(message, "RUN");
+ }, "The SVGScriptElement is initially trusted.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = document.createElementNS(NSURI_SVG, "script");
+ script.textContent = passthroughpolicy.createScript(LOG_RUN_MESSAGE);
+ container.appendChild(script);
+ });
+ }, "Script source set via Element.textContent drops trustworthiness.");
+
+ promise_test(async t => {
+ let script = document.createElement("script");
+ Object.getOwnPropertyDescriptor(Node.prototype, "textContent").set.call(script, LOG_RUN_MESSAGE);
+ assert_equals(script.textContent, LOG_RUN_MESSAGE, "TrustedScript not required.");
+ await no_script_message_for(_ => {
+ container.appendChild(script);
+ });
+ }, "Script source set via Node.textContent drops trustworthiness.");
+
+ promise_test(async t => {
+ await promise_rejects_js(t, TypeError, script_messages_for(_ => {
+ document.createElementNS(NSURI_SVG, "script").innerHTML = LOG_RUN_MESSAGE;
+ }), "TrustedHTML required.");
+ await no_script_message_for(_ => {
+ let script = document.createElementNS(NSURI_SVG, "script");
+ script.innerHTML = passthroughpolicy.createHTML(LOG_RUN_MESSAGE);
+ container.appendChild(script);
+ });
+ }, "Script source set via TrustedHTML sink Element.innerHTML drops trustworthiness.");
+
+ promise_test(async t => {
+ await promise_rejects_js(t, TypeError, script_messages_for(_ => {
+ document.createElement("script").outerHTML = LOG_RUN_MESSAGE;
+ }), "TrustedHTML required.");
+ await no_script_message_for(_ => {
+ let script = document.getElementById("scriptForOuterHTMLTest");
+ script.remove();
+ script.removeAttribute("type");
+ script.firstElementChild.outerHTML = passthroughpolicy.createHTML(LOG_RUN_MESSAGE);
+ container.appendChild(script);
+ });
+ }, "Script source set via TrustedHTML sink Element.outerHTML drops trustworthiness.");
+
+ promise_test(async t => {
+ await promise_rejects_js(t, TypeError, script_messages_for(_ => {
+ document.createElementNS(NSURI_SVG, "script").setHTMLUnsafe(LOG_RUN_MESSAGE);
+ }), "TrustedHTML required.");
+ await no_script_message_for(_ => {
+ let script = document.createElementNS(NSURI_SVG, "script");
+ script.setHTMLUnsafe(passthroughpolicy.createHTML(LOG_RUN_MESSAGE));
+ container.appendChild(script);
+ });
+ }, "Script source set via TrustedHTML sink Element.setHTMLUnsafe() drops trustworthiness.");
+
+ if (SVGScriptElement.prototype.setHTML) {
+ promise_test(async t => {
+ // https://wicg.github.io/sanitizer-api/#set-and-filter-html
+ let script = document.createElementNS(NSURI_SVG, "script");
+ script.setHTML(LOG_RUN_MESSAGE);
+ assert_equals(script.textContent, "");
+ }, "Script source cannot be set via Element.setHTML().");
+ }
+
+ promise_test(async t => {
+ let message = await script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`${LOG_RUN_MESSAGE};;;`);
+ script.firstChild.splitText(3);
+ container.appendChild(script);
+ });
+ assert_equals(message, "RUN");
+ }, "Splitting script source via Text.splitText() keeps trustworthiness.");
+
+ promise_test(async t => {
+ let message = await script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`${LOG_RUN_MESSAGE};;;`);
+ script.firstChild.splitText(3);
+ script.normalize();
+ container.appendChild(script);
+ });
+ assert_equals(message, "RUN");
+ }, "Normalizing script source via Element.normalize() keeps trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.firstChild.nodeValue = LOG_RUN_MESSAGE;
+ container.appendChild(script);
+ });
+ }, "Script source set via Node.nodeValue drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.firstChild.data = LOG_RUN_MESSAGE;
+ container.appendChild(script);
+ });
+ }, "Setting script source via CharacterData.data drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.firstChild.appendData(LOG_RUN_MESSAGE);
+ container.appendChild(script);
+ });
+ }, "Setting script source via CharacterData.appendData() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.firstChild.insertData(0, LOG_RUN_MESSAGE);
+ container.appendChild(script);
+ });
+ }, "Setting script source via CharacterData.insertData() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.firstChild.replaceData(0, 0, LOG_RUN_MESSAGE);
+ container.appendChild(script);
+ });
+ }, "Setting script source via CharacterData.replaceData() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`//${LOG_RUN_MESSAGE}`);
+ script.firstChild.deleteData(0, 2);
+ container.appendChild(script);
+ });
+ }, "Setting script source via CharacterData.deleteData() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.firstChild.before(LOG_RUN_MESSAGE);
+ container.appendChild(script);
+ });
+ }, "Setting script source via CharacterData.before() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.firstChild.after(LOG_RUN_MESSAGE);
+ container.appendChild(script);
+ });
+ }, "Setting script source via CharacterData.after() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`;;;${LOG_RUN_MESSAGE}`);
+ script.firstChild.splitText(3);
+ script.firstChild.remove();
+ container.appendChild(script);
+ });
+ }, "Setting script source via CharacterData.remove() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.firstChild.replaceWith(document.createTextNode(LOG_RUN_MESSAGE));
+ container.appendChild(script);
+ });
+ }, "Setting script source via CharacterData.replaceWith() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.appendChild(document.createTextNode(LOG_RUN_MESSAGE));
+ container.appendChild(script);
+ });
+ }, "Setting script source via Node.appendChild() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.insertBefore(document.createTextNode(LOG_RUN_MESSAGE), script.firstChild);
+ container.appendChild(script);
+ });
+ }, "Setting script source via Node.insertBefore() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.replaceChild(document.createTextNode(LOG_RUN_MESSAGE), script.firstChild);
+ container.appendChild(script);
+ });
+ }, "Setting script source via Node.replaceChild() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`;;;${LOG_RUN_MESSAGE}`);
+ script.firstChild.splitText(3);
+ script.removeChild(script.firstChild);
+ container.appendChild(script);
+ });
+ }, "Setting script source via Node.removeChild() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.prepend(document.createTextNode(LOG_RUN_MESSAGE));
+ container.appendChild(script);
+ });
+ }, "Setting script source via Element.prepend() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.append(document.createTextNode(LOG_RUN_MESSAGE));
+ container.appendChild(script);
+ });
+ }, "Setting script source via Element.append() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.replaceChildren(document.createTextNode(LOG_RUN_MESSAGE));
+ container.appendChild(script);
+ });
+ }, "Setting script source via Element.replaceChildren() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ // Per https://dom.spec.whatwg.org/#move, step 1, moveBefore requires
+ // the two nodes to have the same shadow-including root.
+ let text = document.createTextNode(LOG_RUN_MESSAGE);
+ let root = document.createElement("div");
+ root.appendChild(text);
+ root.appendChild(script);
+ script.moveBefore(text, script.firstChild);
+ container.appendChild(script);
+ });
+ }, "Setting script source via Element.moveBefore() drops trustworthiness.");
+
+ promise_test(async t => {
+ await promise_rejects_js(t, TypeError, script_messages_for(_ => {
+ document.createElementNS(NSURI_SVG, "script").insertAdjacentHTML("afterbegin", LOG_RUN_MESSAGE);
+ }), "TrustedHTML required.");
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.insertAdjacentHTML("afterbegin", passthroughpolicy.createHTML(LOG_RUN_MESSAGE));
+ container.appendChild(script);
+ });
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.insertAdjacentHTML("beforeend", passthroughpolicy.createHTML(LOG_RUN_MESSAGE));
+ container.appendChild(script);
+ });
+ }, "Setting script source via TrustedHTML sink Node.insertAdjacentHTML() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.insertAdjacentText("afterbegin", LOG_RUN_MESSAGE);
+ container.appendChild(script);
+ });
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ script.insertAdjacentText("beforeend", LOG_RUN_MESSAGE);
+ container.appendChild(script);
+ });
+ }, "Setting script source via Node.insertAdjacentText() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_html_script_with_trusted_source_text(`;`);
+ let range = new Range();
+ range.selectNode(script.firstChild);
+ range.insertNode(document.createTextNode(LOG_RUN_MESSAGE));
+ container.appendChild(script);
+ });
+ }, "Setting script source via Range.insertNode() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`//;;;${LOG_RUN_MESSAGE}`);
+ script.firstChild.splitText(2);
+ let range = new Range();
+ range.setStart(script.firstChild, 0);
+ range.setEnd(script.lastChild, 3);
+ range.deleteContents();
+ container.appendChild(script);
+ });
+ }, "Setting script source via Range.deleteContents() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`${LOG_RUN_MESSAGE}`);
+ let clone = script.cloneNode(true);
+ container.appendChild(clone);
+ });
+ }, "Cloning a script via Node.cloneNode() drops trustworthiness.");
+
+ promise_test(async t => {
+ await no_script_message_for(_ => {
+ let div = document.createElement("div");
+ let script = create_svg_script_with_trusted_source_text(`${LOG_RUN_MESSAGE}`);
+ div.appendChild(script);
+ let range = new Range();
+ range.selectNode(script);
+ let documentFragment = range.cloneContents();
+ container.appendChild(documentFragment.firstElementChild);
+ });
+ }, "Cloning a script via Range.cloneContents() drops trustworthiness.");
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-004.html b/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-004.html
new file mode 100644
index 00000000000..90081d16ab9
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-004.html
@@ -0,0 +1,449 @@
+<!DOCTYPE html>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/namespaces.js"></script>
+<script src="support/passthroughpolicy.js"></script>
+<script src="support/script-messages.js"></script>
+<link rel="help" href="https://w3c.github.io/trusted-types/dist/spec/#enforcement-in-scripts">
+<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script';">
+<!-- This test is similar to script-enforcement-002 but for the
+ SVGScriptElement, which has slightly different behavior:
+ - No equivalent to HTMLElement.innerText.
+ - No equivalent to HTMLScriptElement.text.
+ - innerHTML and textContent are not Trusted sinks.
+ - The HTML parser can insert elements inside the <script> tag.
+ - Sink name uses "SVGScriptElement".
+ -->
+<svg>
+ <!-- Provide some static SVGScriptElements for use by
+ document.createElementNS(NSURI_SVG, "script"). See explanation in script-messages.js. -->
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">;</script>
+ <script type="unknown">//;;;window.log_message("RUN")</script>
+ <script type="unknown">//;;;window.log_message("RUN")</script>
+ <script type="unknown">//window.log_message("RUN")</script>
+ <script type="unknown">;;;window.log_message("RUN")/////</script>
+ <script type="unknown">;;;window.log_message("RUN")</script>
+ <script type="unknown">;;;window.log_message("RUN")</script>
+ <script type="unknown">;;;window.log_message("RUN")</script>
+ <script type="unknown">window.log_message("RUN");;;</script>
+ <script type="unknown">window.log_message("RUN");;;</script>
+ <script type="unknown">window.log_message("RUN")</script>
+ <script type="unknown">window.log_message("RUN")</script>
+ <script type="unknown">window.log_message("RUN")</script>
+</svg>
+<svg>
+ <script id="scriptForOuterHTMLTest" type="unknown"><g></g></script>
+</svg>
+<svg id="container"></svg>
+<script>
+ trustedTypes.createPolicy("default", {
+ createHTML: (value, _, sink) => {
+ window.log_message("CREATE_HTML");
+ window.log_message(sink);
+ return value.replace("RUN", "RUN_TRUSTED_HTML");
+ },
+ createScript: (value, _, sink) => {
+ window.log_message("CREATE_SCRIPT");
+ window.log_message(sink);
+ return value.replace("RUN", "RUN_TRUSTED_SCRIPT");
+ },
+ });
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = document.createElementNS(NSURI_SVG, "script");
+ window.log_message("SET");
+ script.textContent = LOG_RUN_MESSAGE;
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via SVGScriptElement.textContent.");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = document.createElement("script");
+ window.log_message("SET");
+ Object.getOwnPropertyDescriptor(Node.prototype, "textContent").set.call(script, LOG_RUN_MESSAGE);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "HTMLScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Verify when the default policy is called for script set source via Node.textContent.");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = document.createElementNS(NSURI_SVG, "script");
+ window.log_message("SET");
+ script.innerHTML = LOG_RUN_MESSAGE;
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "CREATE_HTML", "Element innerHTML", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT_TRUSTED_HTML"]);
+ }, "Default policy's calls when setting script source via Element.innerHTML.");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = document.getElementById("scriptForOuterHTMLTest");
+ script.remove();
+ script.removeAttribute("type");
+ window.log_message("SET");
+ script.firstElementChild.outerHTML = LOG_RUN_MESSAGE;
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "CREATE_HTML", "Element outerHTML", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT_TRUSTED_HTML"]);
+ }, "Default policy's calls when setting script source via Element.outerHTML.");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = document.createElementNS(NSURI_SVG, "script");
+ window.log_message("SET");
+ script.setHTMLUnsafe(LOG_RUN_MESSAGE);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "CREATE_HTML", "Element setHTMLUnsafe", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT_TRUSTED_HTML"]);
+ }, "Default policy's calls when setting script source via Element.setHTMLUnsafe().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`${LOG_RUN_MESSAGE};;;`);
+ window.log_message("SET");
+ script.firstChild.splitText(3);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "RUN"]);
+ }, "Default policy when splitting script source via Text.splitText().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`${LOG_RUN_MESSAGE};;;`);
+ script.firstChild.splitText(3);
+ window.log_message("SET");
+ script.normalize();
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "RUN"]);
+ }, "Default policy when normalizing script source via Element.normalize().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.firstChild.nodeValue = LOG_RUN_MESSAGE;
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via Node.nodeValue.");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.firstChild.data = LOG_RUN_MESSAGE;
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via CharacterData.data.");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.firstChild.appendData(LOG_RUN_MESSAGE);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via CharacterData.appendData().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.firstChild.insertData(0, LOG_RUN_MESSAGE);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via CharacterData.insertData().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.firstChild.replaceData(0, 0, LOG_RUN_MESSAGE);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via CharacterData.replaceData().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`//${LOG_RUN_MESSAGE}`);
+ window.log_message("SET");
+ script.firstChild.deleteData(0, 2);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via CharacterData.deleteData().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.firstChild.before(LOG_RUN_MESSAGE);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via CharacterData.before().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.firstChild.after(LOG_RUN_MESSAGE);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via CharacterData.after().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`;;;${LOG_RUN_MESSAGE}`);
+ script.firstChild.splitText(3);
+ window.log_message("SET");
+ script.firstChild.remove();
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via CharacterData.remove().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.firstChild.replaceWith(document.createTextNode(LOG_RUN_MESSAGE));
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via CharacterData.replaceWith().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.appendChild(document.createTextNode(LOG_RUN_MESSAGE));
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via Node.appendChild().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.insertBefore(document.createTextNode(LOG_RUN_MESSAGE), script.firstChild);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via Node.insertBefore().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.replaceChild(document.createTextNode(LOG_RUN_MESSAGE), script.firstChild);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via Node.replaceChild().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`;;;${LOG_RUN_MESSAGE}`);
+ script.firstChild.splitText(3);
+ window.log_message("SET");
+ script.removeChild(script.firstChild);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via Node.removeChild().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.prepend(document.createTextNode(LOG_RUN_MESSAGE));
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via Element.prepend().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.append(document.createTextNode(LOG_RUN_MESSAGE));
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via Element.append().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.replaceChildren(document.createTextNode(LOG_RUN_MESSAGE));
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via Element.replaceChildren().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ // Per https://dom.spec.whatwg.org/#move, step 1, moveBefore requires
+ // the two nodes to have the same shadow-including root.
+ let text = document.createTextNode(LOG_RUN_MESSAGE);
+ let root = document.createElement("div");
+ root.appendChild(text);
+ root.appendChild(script);
+ script.moveBefore(text, script.firstChild);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via Element.moveBefore().");
+
+ promise_test(async t => {
+ let messages1 = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.insertAdjacentText("afterbegin", LOG_RUN_MESSAGE);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages1, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ let messages2 = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.insertAdjacentText("beforeend", LOG_RUN_MESSAGE);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages2, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via Node.insertAdjacentText().");
+
+ promise_test(async t => {
+ let messages1 = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.insertAdjacentHTML("afterbegin", LOG_RUN_MESSAGE);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages1, ["SET", "CREATE_HTML", "Element insertAdjacentHTML", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT_TRUSTED_HTML"]);
+ let messages2 = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(";");
+ window.log_message("SET");
+ script.insertAdjacentHTML("beforeend", LOG_RUN_MESSAGE);
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages2, ["SET", "CREATE_HTML", "Element insertAdjacentHTML", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT_TRUSTED_HTML"]);
+ }, "Default policy's calls when setting script source via Node.insertAdjacentHTML().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_html_script_with_trusted_source_text(`;`);
+ let range = new Range();
+ range.selectNode(script.firstChild);
+ window.log_message("SET");
+ range.insertNode(document.createTextNode(LOG_RUN_MESSAGE));
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "HTMLScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting source via Range.insertNode().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`//;;;${LOG_RUN_MESSAGE}`);
+ script.firstChild.splitText(2);
+ let range = new Range();
+ range.setStart(script.firstChild, 0);
+ range.setEnd(script.lastChild, 3);
+ window.log_message("SET");
+ range.deleteContents();
+ window.log_message("APPEND");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["SET", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when setting script source via Range.deleteContents().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_trusted_source_text(`${LOG_RUN_MESSAGE}`);
+ window.log_message("CLONE");
+ let clone = script.cloneNode(true);
+ window.log_message("APPEND");
+ container.appendChild(clone);
+ });
+ assert_array_equals(messages, ["CLONE", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when cloning a script via Node.cloneNode().");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let div = document.createElement("div");
+ let script = create_svg_script_with_trusted_source_text(`${LOG_RUN_MESSAGE}`);
+ div.appendChild(script);
+ let range = new Range();
+ range.selectNode(script);
+ window.log_message("CLONE");
+ let documentFragment = range.cloneContents();
+ window.log_message("APPEND");
+ container.appendChild(documentFragment.firstElementChild);
+ });
+ assert_array_equals(messages, ["CLONE", "APPEND", "CREATE_SCRIPT", "SVGScriptElement text", "RUN_TRUSTED_SCRIPT"]);
+ }, "Default policy's calls when cloning a script via Range.cloneContents().");
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-007.html b/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-007.html
new file mode 100644
index 00000000000..822373c5a6d
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-007.html
@@ -0,0 +1,97 @@
+<!DOCTYPE html>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/namespaces.js"></script>
+<script src="support/passthroughpolicy.js"></script>
+<script src="support/script-messages.js"></script>
+<link rel="help" href="https://w3c.github.io/trusted-types/dist/spec/#enforcement-in-scripts">
+<link rel="help" href="https://html.spec.whatwg.org/#prepare-the-script-element">
+<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'">
+<!-- This is the same test as script-enforcement-006 but for SVGScriptElement. -->
+<svg id="container"></svg>
+<script>
+ const logMessageModulePath = "./support/logMessage-module.sub.js";
+
+ // Define a default policy that transforms the script's type to some valid
+ // source content.
+ trustedTypes.createPolicy("default", {
+ createScript: (value, _, sink) => {
+ window.log_message("CREATE_SCRIPT");
+ window.log_message(sink);
+ switch (value) {
+ case "classic":
+ return `window.log_message('CLASSIC');`;
+ case "module":
+ return `window.log_message('MODULE');`;
+ case "importmap":
+ return `{ "imports": { "${logMessageModulePath}?message=UNMAPPED": "${logMessageModulePath}?message=IMPORTMAP" }}`;
+ case "importmap2":
+ return `{ "imports": { "${logMessageModulePath}?message=UNMAPPED2": "${logMessageModulePath}?message=IMPORTMAP2" }}`;
+ case "importmap3":
+ return `{ "imports": { "${logMessageModulePath}?message=UNMAPPED3": "${logMessageModulePath}?message=IMPORTMAP3" }}`;
+ }
+ }
+ });
+
+ promise_test(async t => {
+ let messages = await script_messages_for(_ => {
+ let script = create_svg_script_with_untrusted_source_text("classic");
+ script.setAttribute("type", "application/ecmascript");
+ // Appending the script will log "CLASSIC".
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["CREATE_SCRIPT", "SVGScriptElement text", "CLASSIC"]);
+ }, "Untrusted SVGScriptElement with classic type uses the source text returned by the default policy.");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(async _ => {
+ let script = create_svg_script_with_untrusted_source_text("importmap");
+ script.setAttribute("type", "importmap");
+
+ // Appending the script sets up an import map for logMessageModulePath.
+ container.appendChild(script);
+
+ // Importing logMessageModulePath will log message "IMPORTMAP".
+ await import(`${logMessageModulePath}?message=UNMAPPED`);
+ });
+ assert_array_equals(messages, ["CREATE_SCRIPT", "SVGScriptElement text", "IMPORTMAP"]);
+ }, "Untrusted SVGScriptElement of importmap type uses the source text returned by the default policy.");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(async _ => {
+ let script = create_svg_script_with_untrusted_source_text("module");
+ script.setAttribute("type", "module");
+
+ // Appending the script will log message "MODULE".
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["CREATE_SCRIPT", "SVGScriptElement text", "MODULE"]);
+ }, "Untrusted SVGScriptElement of module type uses the source text returned by the default policy.");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(async _ => {
+ let script2 = create_svg_script_with_untrusted_source_text("importmap2");
+ script2.setAttribute("type", "importmap");
+
+ // Appending the script sets up an import map for logMessageModulePath.
+ container.appendChild(script2);
+
+ // Importing logMessageModulePath will log message "IMPORTMAP2".
+ await import(`${logMessageModulePath}?message=UNMAPPED2`);
+
+ let script3 = create_svg_script_with_untrusted_source_text("importmap3");
+ script3.setAttribute("type", "importmap");
+
+ // Appending the script sets up an import map for logMessageModulePath.
+ container.appendChild(script3);
+
+ // Importing logMessageModulePath will log message "IMPORTMAP3".
+ await import(`${logMessageModulePath}?message=UNMAPPED3`);
+ });
+ assert_array_equals(messages,
+ ["CREATE_SCRIPT", "SVGScriptElement text", "IMPORTMAP2",
+ "CREATE_SCRIPT", "SVGScriptElement text", "IMPORTMAP3"]);
+ }, "Untrusted SVGScriptElement of two importmap type use the source text returned by the default policy.");
+
+
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-011.html b/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-011.html
new file mode 100644
index 00000000000..d811c774488
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/trusted-types/script-enforcement-011.html
@@ -0,0 +1,47 @@
+<!DOCTYPE html>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="support/namespaces.js"></script>
+<script src="support/passthroughpolicy.js"></script>
+<script src="support/script-messages.js"></script>
+<link rel="help" href="https://w3c.github.io/trusted-types/dist/spec/#enforcement-in-scripts">
+<link rel="help" href="https://html.spec.whatwg.org/#prepare-the-script-element">
+<meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'">
+<div id="container"></div>
+<script>
+ let script;
+ const checkScriptType = "try { undefined = 0; window.log_message('CLASSIC'); } catch(e) { window.log_message('MODULE'); }";
+
+ // Define a default policy that change the script's type.
+ trustedTypes.createPolicy("default", {
+ createScript: (value, _, sink) => {
+ window.log_message("CREATE_SCRIPT");
+ window.log_message(sink);
+ if (script.hasAttribute("type")) {
+ script.removeAttribute("type");
+ } else {
+ script.setAttribute("type", "module");
+ }
+ return value;
+ }
+ });
+
+ promise_test(async t => {
+ let messages = await script_messages_for(async _ => {
+ t.add_cleanup(_ => { script = null });
+ script = create_svg_script_with_untrusted_source_text(checkScriptType);
+ script.setAttribute("type", "module");
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["CREATE_SCRIPT", "SVGScriptElement text", "CLASSIC"]);
+ }, "Changing script's type from classic to module in the default policy works.");
+
+ promise_test(async t => {
+ let messages = await script_messages_for(async _ => {
+ t.add_cleanup(_ => { script = null });
+ script = create_svg_script_with_untrusted_source_text(checkScriptType);
+ container.appendChild(script);
+ });
+ assert_array_equals(messages, ["CREATE_SCRIPT", "SVGScriptElement text", "MODULE"]);
+ }, "Changing script's type from module to classic in the default policy works.");
+</script>