Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

feat(cli): add disable-js fetch mode

ldm028aaaa9e8a76
diff --git a/moli-core/Cargo.toml b/moli-core/Cargo.toml
index da64ccff4..18f0629fb 100644
--- a/moli-core/Cargo.toml
+++ b/moli-core/Cargo.toml
@@ -36,6 +36,7 @@ url = "2.5.7"
[dev-dependencies]
moli-fetch = { path = "../moli-fetch", features = ["test-support"] }
+moli-parser = { path = "../moli-parser", features = ["test-support"] }
# Integration tests compile moli-core as a normal dependency, so `cfg(test)` in
# moli-renderer-v8 would not apply. Enable the renderer feature through this
# dev-dependency instead; production dependencies keep it disabled by default.
diff --git a/moli-core/src/config/mod.rs b/moli-core/src/config/mod.rs
index c80231e93..360c8c464 100644
--- a/moli-core/src/config/mod.rs
+++ b/moli-core/src/config/mod.rs
@@ -11,6 +11,7 @@ pub struct BrowserConfig {
layout_policy: LayoutPolicy,
optional_resource_fetch_mask: OptionalResourceFetchMask,
subframe_loading_enabled: bool,
+ script_execution_disabled: bool,
wpt_extensions_enabled: bool,
}
@@ -23,6 +24,7 @@ impl Default for BrowserConfig {
layout_policy: LayoutPolicy::default(),
optional_resource_fetch_mask: OptionalResourceFetchMask::NONE,
subframe_loading_enabled: true,
+ script_execution_disabled: false,
wpt_extensions_enabled: false,
}
}
@@ -125,6 +127,14 @@ impl BrowserConfig {
self
}
+ pub fn script_execution_disabled(&self) -> bool {
+ self.script_execution_disabled
+ }
+
+ pub fn set_script_execution_disabled(&mut self, disabled: bool) {
+ self.script_execution_disabled = disabled;
+ }
+
pub fn wpt_extensions_enabled(&self) -> bool {
self.wpt_extensions_enabled
}
@@ -209,6 +219,15 @@ mod tests {
}
}
+ #[test]
+ fn browser_config_defaults_to_script_execution_and_can_disable_it() {
+ let mut config = BrowserConfig::default();
+ assert!(!config.script_execution_disabled());
+
+ config.set_script_execution_disabled(true);
+ assert!(config.script_execution_disabled());
+ }
+
#[test]
fn browser_config_toggles_each_optional_resource_bit_independently() {
for (enabled_type, enabled_bit) in OPTIONAL_RESOURCES {
diff --git a/moli-core/src/dom/tests.rs b/moli-core/src/dom/tests.rs
index 6cf1d2af4..330cf3f98 100644
--- a/moli-core/src/dom/tests.rs
+++ b/moli-core/src/dom/tests.rs
@@ -5,7 +5,7 @@ use crate::{parser::HtmlParser, renderer::ReflectorRegistry};
use super::native::{NativeDom, NodeType};
fn parse_fixture(html: &str) -> NativeDom {
- HtmlParser.parse(
+ HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://fixture.moli.local/native-dom.html")
.expect("fixture url must be valid"),
html.to_owned(),
diff --git a/moli-core/src/runtime/mod.rs b/moli-core/src/runtime/mod.rs
index 55ee58dc4..0df1a3e78 100644
--- a/moli-core/src/runtime/mod.rs
+++ b/moli-core/src/runtime/mod.rs
@@ -233,6 +233,10 @@ impl Browser {
config.optional_resource_fetch_mask(),
config.subframe_loading_enabled(),
);
+ // A script-disabled CLI fetch must not execute site-owned JavaScript
+ // through a previously registered Service Worker before the new
+ // Document's own execution policy can take effect.
+ page_network_policy.set_bypass_service_worker(config.script_execution_disabled());
let browser_context_owner =
RendererBrowserContextRuntime::new_owned_with_service_worker_resource_store_and_browser_resource_runtime(
partition.service_worker_resource_store(),
@@ -1126,6 +1130,7 @@ impl Browser {
None,
stage,
);
+ create_page_request.script_execution_disabled = self.config.script_execution_disabled();
create_page_request.wpt_extensions_enabled = self.config.wpt_extensions_enabled();
create_page_request.reply_boundary = reply_boundary;
create_page_request.lifecycle_decider = lifecycle_decider;
@@ -1259,7 +1264,7 @@ impl Browser {
vec![],
None,
None,
- false,
+ self.config.script_execution_disabled(),
false,
1.0,
Default::default(),
diff --git a/moli-core/src/selector/tests/mod.rs b/moli-core/src/selector/tests/mod.rs
index db4c08d66..a4b1e413c 100644
--- a/moli-core/src/selector/tests/mod.rs
+++ b/moli-core/src/selector/tests/mod.rs
@@ -18,7 +18,7 @@ use crate::{
use super::{QueryEngine, error::SelectorErrorKind};
pub(crate) fn parse_document(html: &str) -> NativeDom {
- HtmlParser.parse(
+ HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("http://example.test/").expect("valid test url"),
html.to_owned(),
)
diff --git a/moli-parser/Cargo.toml b/moli-parser/Cargo.toml
index f7ef6abcd..0e29e24b3 100644
--- a/moli-parser/Cargo.toml
+++ b/moli-parser/Cargo.toml
@@ -4,6 +4,12 @@ name = "moli-parser"
version = "0.1.0"
edition = "2024"
+[features]
+default = []
+# Convenience parser policies for fixtures. Production callers must derive the
+# scripting state from the target Document and construct the parser explicitly.
+test-support = []
+
[dependencies]
anyhow = "1.0.100"
html5ever = "0.39.0"
diff --git a/moli-parser/src/html.rs b/moli-parser/src/html.rs
index b1cec45fa..01c48b9df 100644
--- a/moli-parser/src/html.rs
+++ b/moli-parser/src/html.rs
@@ -22,21 +22,30 @@ use moli_stylesheet_blocking::{
DocumentBlockingStylesheetSignature, DocumentOwnedBlockingStylesheetDiscoveryInput,
};
+#[cfg(any(test, feature = "test-support"))]
+use super::live_target::new_live_fragment_root_html_tree_sink_stream;
use super::live_target::{
ParserDomMutationConsumer, ParserDomReadConsumer, ParserElementCreationConsumer,
ParserMutationEffectConsumer, ParserMutationEffectDelivery, ParserRuntimeDomSinks,
ParserStreamHtmlTreeSinkTarget, new_live_document_root_html_tree_sink_stream,
- new_live_fragment_root_html_tree_sink_stream, new_parser_stream_html_tree_sink_stream,
- new_parser_stream_html_tree_sink_target,
+ new_parser_stream_html_tree_sink_stream, new_parser_stream_html_tree_sink_target,
};
use super::{
ParserSourcePosition, html_chunks,
- session::{HtmlParserSession, html_parse_opts, html_parse_opts_with_scripting},
+ session::{HtmlParserSession, html_parse_opts_with_scripting},
stream::HtmlTreeSinkStream,
};
-#[derive(Debug, Clone, Default)]
-pub struct HtmlParser;
+/// HTML parser configured with the scripting state of the target `Document`.
+///
+/// This state controls HTML parsing semantics such as `<noscript>` tokenization;
+/// it does not execute JavaScript. Callers must choose the state explicitly so
+/// detached and sandboxed documents cannot accidentally inherit the normal
+/// browsing-context default.
+#[derive(Debug, Clone, Copy)]
+pub struct HtmlParser {
+ scripting_enabled: bool,
+}
#[derive(Clone, Debug)]
pub struct ParserInputSession(Rc<RefCell<ParserInputState>>);
@@ -130,13 +139,47 @@ pub enum ParserScriptHandoff {
impl ParserScriptHandoff {
pub fn node_id(&self) -> NativeNodeId {
+ self.start_position().0
+ }
+
+ pub fn start_position(&self) -> (NativeNodeId, u64, u64) {
match self {
- Self::BlockingClassic { node_id, .. }
- | Self::AsyncPostParse { node_id, .. }
- | Self::NonAsyncPostParse { node_id, .. }
- | Self::ImportMap { node_id, .. }
- | Self::NoExecution { node_id, .. }
- | Self::PreparationFailure { node_id, .. } => *node_id,
+ Self::BlockingClassic {
+ node_id,
+ start_line,
+ start_column,
+ ..
+ }
+ | Self::AsyncPostParse {
+ node_id,
+ start_line,
+ start_column,
+ ..
+ }
+ | Self::NonAsyncPostParse {
+ node_id,
+ start_line,
+ start_column,
+ ..
+ }
+ | Self::ImportMap {
+ node_id,
+ start_line,
+ start_column,
+ ..
+ }
+ | Self::NoExecution {
+ node_id,
+ start_line,
+ start_column,
+ ..
+ }
+ | Self::PreparationFailure {
+ node_id,
+ start_line,
+ start_column,
+ ..
+ } => (*node_id, *start_line, *start_column),
}
}
}
@@ -331,6 +374,18 @@ pub(super) struct DocumentSink {
}
impl HtmlParser {
+ /// Convenience policy for tests that model an executable `Document`.
+ #[cfg(any(test, feature = "test-support"))]
+ pub const SCRIPTING_ENABLED: Self = Self::with_scripting_enabled(true);
+
+ /// Convenience policy for tests that model a non-executable `Document`.
+ #[cfg(any(test, feature = "test-support"))]
+ pub const SCRIPTING_DISABLED: Self = Self::with_scripting_enabled(false);
+
+ pub const fn with_scripting_enabled(scripting_enabled: bool) -> Self {
+ Self { scripting_enabled }
+ }
+
pub fn parse(&self, final_url: Url, html: String) -> NativeDom {
self.parse_dom_host(final_url, html).into_dom()
}
@@ -350,7 +405,8 @@ impl HtmlParser {
) -> NativeDom {
let target =
ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots(final_url, false);
- let mut stream = HtmlTreeSinkStream::from_target(target);
+ let mut stream =
+ HtmlTreeSinkStream::from_target_with_scripting(target, self.scripting_enabled);
for chunk in html_chunks(&html) {
stream.feed(chunk);
}
@@ -358,7 +414,7 @@ impl HtmlParser {
}
pub fn start_document(&self, final_url: Url) -> DocumentStream {
- DocumentStream::new_parser_stream(final_url)
+ DocumentStream::new_parser_stream(final_url, self.scripting_enabled)
}
pub fn start_live_document_root(
@@ -366,7 +422,7 @@ impl HtmlParser {
final_url: Url,
document_handle: NativeNodeId,
) -> DocumentStream {
- DocumentStream::new_live_document_root(final_url, document_handle)
+ DocumentStream::new_live_document_root(final_url, document_handle, self.scripting_enabled)
}
pub fn parse_fragment(
@@ -382,7 +438,7 @@ impl HtmlParser {
context_local_name,
html,
true,
- true,
+ self.scripting_enabled,
)
}
@@ -392,23 +448,6 @@ impl HtmlParser {
context_namespace: &str,
context_local_name: &str,
html: String,
- ) -> NativeDom {
- self.parse_fragment_without_declarative_shadow_roots_with_scripting(
- final_url,
- context_namespace,
- context_local_name,
- html,
- true,
- )
- }
-
- pub fn parse_fragment_without_declarative_shadow_roots_with_scripting(
- &self,
- final_url: Url,
- context_namespace: &str,
- context_local_name: &str,
- html: String,
- scripting_enabled: bool,
) -> NativeDom {
self.parse_fragment_with_declarative_shadow_roots(
final_url,
@@ -416,7 +455,7 @@ impl HtmlParser {
context_local_name,
html,
false,
- scripting_enabled,
+ self.scripting_enabled,
)
}
@@ -468,8 +507,12 @@ impl HtmlParser {
);
let context_handle = ParseHandle::new_synthetic_fragment_context(Rc::new(context));
let sink = DocumentSink::new(target);
- let mut parser =
- HtmlParserSession::new_fragment(sink, html_parse_opts(), context_handle, true);
+ let mut parser = HtmlParserSession::new_fragment(
+ sink,
+ html_parse_opts_with_scripting(self.scripting_enabled),
+ context_handle,
+ self.scripting_enabled,
+ );
for chunk in html_chunks(&html) {
parser.process(StrTendril::from(chunk));
@@ -485,20 +528,29 @@ impl Default for ParserInputQueue {
}
impl DocumentStream {
- fn new_parser_stream(final_url: Url) -> Self {
+ fn new_parser_stream(final_url: Url, scripting_enabled: bool) -> Self {
Self {
- inner: new_parser_stream_html_tree_sink_stream(final_url),
+ inner: new_parser_stream_html_tree_sink_stream(final_url, scripting_enabled),
input: HtmlParserInputStream::default(),
}
}
- fn new_live_document_root(final_url: Url, document_handle: NativeNodeId) -> Self {
+ fn new_live_document_root(
+ final_url: Url,
+ document_handle: NativeNodeId,
+ scripting_enabled: bool,
+ ) -> Self {
Self {
- inner: new_live_document_root_html_tree_sink_stream(final_url, document_handle),
+ inner: new_live_document_root_html_tree_sink_stream(
+ final_url,
+ document_handle,
+ scripting_enabled,
+ ),
input: HtmlParserInputStream::default(),
}
}
+ #[cfg(any(test, feature = "test-support"))]
fn new_live_fragment_root(
final_url: Url,
fragment_handle: NativeNodeId,
@@ -507,6 +559,7 @@ impl DocumentStream {
context_local_name: &str,
runtime_dom_sinks: ParserRuntimeDomSinks,
allow_declarative_shadow_roots: bool,
+ scripting_enabled: bool,
) -> Self {
Self {
inner: new_live_fragment_root_html_tree_sink_stream(
@@ -517,26 +570,31 @@ impl DocumentStream {
context_local_name,
runtime_dom_sinks,
allow_declarative_shadow_roots,
+ scripting_enabled,
),
input: HtmlParserInputStream::default(),
}
}
+ #[cfg(any(test, feature = "test-support"))]
pub fn is_parser_stream_backend_for_testing(&self) -> bool {
true
}
- pub fn new_parser_stream_for_testing(final_url: Url) -> Self {
- Self::new_parser_stream(final_url)
+ #[cfg(any(test, feature = "test-support"))]
+ pub fn new_scripting_enabled_parser_stream_for_testing(final_url: Url) -> Self {
+ Self::new_parser_stream(final_url, true)
}
- pub fn new_live_document_root_for_testing(
+ #[cfg(any(test, feature = "test-support"))]
+ pub fn new_scripting_enabled_live_document_root_for_testing(
final_url: Url,
document_handle: NativeNodeId,
) -> Self {
- Self::new_live_document_root(final_url, document_handle)
+ Self::new_live_document_root(final_url, document_handle, true)
}
+ #[cfg(any(test, feature = "test-support"))]
pub fn new_live_fragment_root_for_testing<T>(
final_url: Url,
fragment_handle: NativeNodeId,
@@ -545,6 +603,7 @@ impl DocumentStream {
context_local_name: &str,
consumer: &mut T,
allow_declarative_shadow_roots: bool,
+ scripting_enabled: bool,
) -> Self
where
T: ParserDomReadConsumer + ParserDomMutationConsumer + ParserMutationEffectConsumer,
@@ -561,6 +620,7 @@ impl DocumentStream {
context_local_name,
runtime_dom_sinks,
allow_declarative_shadow_roots,
+ scripting_enabled,
)
}
@@ -648,6 +708,7 @@ impl DocumentStream {
pending
}
+ #[cfg(any(test, feature = "test-support"))]
pub fn queued_end_segment_count_for_testing(&self) -> usize {
self.input.end_segments.len()
}
@@ -1686,12 +1747,19 @@ mod tests {
const MATHML_NS: &str = "http://www.w3.org/1998/Math/MathML";
fn parse_test_document(html: &str) -> NativeDom {
- HtmlParser.parse(
+ HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.test/").expect("test url"),
html.to_owned(),
)
}
+ fn parse_test_document_with_scripting(html: &str, scripting_enabled: bool) -> NativeDom {
+ let mut stream = HtmlParser::with_scripting_enabled(scripting_enabled)
+ .start_document(Url::parse("https://example.test/").expect("test url"));
+ stream.feed(html);
+ stream.finish()
+ }
+
fn first_element_by_ns(
document: &NativeDom,
namespace: &str,
@@ -1731,9 +1799,80 @@ mod tests {
);
}
+ #[test]
+ fn document_scripting_flag_controls_noscript_tokenization() {
+ let html = concat!(
+ "<!doctype html><html><head>",
+ "<noscript><link id='fallback-style' rel='stylesheet' href='/fallback.css'></noscript>",
+ "</head><body>",
+ "<noscript><main id='fallback'>fallback</main></noscript>",
+ "</body></html>",
+ );
+
+ let disabled = parse_test_document_with_scripting(html, false);
+ assert_eq!(
+ disabled
+ .elements_by_tag_name_ns(disabled.document_node_id(), Some(HTML_NS), "link", true,)
+ .len(),
+ 1,
+ "head noscript content must be parsed as markup when scripting is disabled"
+ );
+ assert_eq!(
+ disabled
+ .elements_by_tag_name_ns(disabled.document_node_id(), Some(HTML_NS), "main", true,)
+ .len(),
+ 1,
+ "body noscript content must be parsed as markup when scripting is disabled"
+ );
+
+ let enabled = parse_test_document_with_scripting(html, true);
+ assert!(
+ enabled
+ .elements_by_tag_name_ns(enabled.document_node_id(), Some(HTML_NS), "link", true,)
+ .is_empty(),
+ "head noscript markup must remain inert when scripting is enabled"
+ );
+ assert!(
+ enabled
+ .elements_by_tag_name_ns(enabled.document_node_id(), Some(HTML_NS), "main", true,)
+ .is_empty(),
+ "body noscript markup must remain raw text when scripting is enabled"
+ );
+ }
+
+ #[test]
+ fn fragment_scripting_flag_controls_noscript_tokenization() {
+ let parse = |scripting_enabled| {
+ HtmlParser::with_scripting_enabled(scripting_enabled)
+ .parse_fragment_without_declarative_shadow_roots(
+ Url::parse("https://example.test/").expect("test url"),
+ HTML_NS,
+ "body",
+ "<noscript><span id='fallback'></span></noscript>".to_owned(),
+ )
+ };
+
+ let disabled = parse(false);
+ assert_eq!(
+ disabled
+ .elements_by_tag_name_ns(disabled.document_node_id(), Some(HTML_NS), "span", true,)
+ .len(),
+ 1,
+ "a scripting-disabled fragment must parse noscript children as markup"
+ );
+
+ let enabled = parse(true);
+ assert!(
+ enabled
+ .elements_by_tag_name_ns(enabled.document_node_id(), Some(HTML_NS), "span", true,)
+ .is_empty(),
+ "a scripting-enabled fragment must keep noscript children as text"
+ );
+ }
+
#[test]
fn template_contents_do_not_publish_document_stylesheet_candidates() {
- let document = HtmlParser.parse_dom_host(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse_dom_host(
Url::parse("https://template-styles.test/page.html").expect("test URL"),
concat!(
"<!doctype html>",
diff --git a/moli-parser/src/live_target.rs b/moli-parser/src/live_target.rs
index 5986ed1e9..8c5c3a314 100644
--- a/moli-parser/src/live_target.rs
+++ b/moli-parser/src/live_target.rs
@@ -1969,6 +1969,7 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
+ #[cfg(any(test, feature = "test-support"))]
pub(super) fn new_live_fragment_root(
final_url: Url,
fragment_handle: NativeNodeId,
@@ -3317,20 +3318,28 @@ pub(super) fn new_parser_stream_html_tree_sink_target(
ParserStreamHtmlTreeSinkTarget::new(final_url)
}
-pub(super) fn new_parser_stream_html_tree_sink_stream(final_url: Url) -> HtmlTreeSinkStream {
- HtmlTreeSinkStream::from_target(new_parser_stream_html_tree_sink_target(final_url))
+pub(super) fn new_parser_stream_html_tree_sink_stream(
+ final_url: Url,
+ scripting_enabled: bool,
+) -> HtmlTreeSinkStream {
+ HtmlTreeSinkStream::from_target_with_scripting(
+ new_parser_stream_html_tree_sink_target(final_url),
+ scripting_enabled,
+ )
}
pub(super) fn new_live_document_root_html_tree_sink_stream(
final_url: Url,
document_handle: NativeNodeId,
+ scripting_enabled: bool,
) -> HtmlTreeSinkStream {
- HtmlTreeSinkStream::from_target(ParserStreamHtmlTreeSinkTarget::new_live_document_root(
- final_url,
- document_handle,
- ))
+ HtmlTreeSinkStream::from_target_with_scripting(
+ ParserStreamHtmlTreeSinkTarget::new_live_document_root(final_url, document_handle),
+ scripting_enabled,
+ )
}
+#[cfg(any(test, feature = "test-support"))]
pub(super) fn new_live_fragment_root_html_tree_sink_stream(
final_url: Url,
fragment_handle: NativeNodeId,
@@ -3339,6 +3348,7 @@ pub(super) fn new_live_fragment_root_html_tree_sink_stream(
context_local_name: &str,
runtime_dom_sinks: ParserRuntimeDomSinks,
allow_declarative_shadow_roots: bool,
+ scripting_enabled: bool,
) -> HtmlTreeSinkStream {
let mut stream = HtmlTreeSinkStream::from_fragment_target(
ParserStreamHtmlTreeSinkTarget::new_live_fragment_root(
@@ -3350,6 +3360,7 @@ pub(super) fn new_live_fragment_root_html_tree_sink_stream(
context_handle,
context_namespace,
context_local_name,
+ scripting_enabled,
);
stream.clear_runtime_dom_sinks_after_parse_step();
stream
@@ -3439,11 +3450,12 @@ fn parser_stream_html_tree_sink_target_builds_dom_and_records_parser_state() {
let html = "<!doctype html><html><head><template id=t><span>inner</span></template><script>window.inline = true;</script><script async src=\"/async.js\"></script></head><body><div>hello</div></body></html>";
let url = Url::parse("https://example.test/").expect("test url");
- let mut live = crate::DocumentStream::new_parser_stream_for_testing(url.clone());
+ let mut live =
+ crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url.clone());
for chunk in html_chunks(html) {
live.feed(chunk);
}
- let parser = crate::HtmlParser;
+ let parser = crate::HtmlParser::SCRIPTING_ENABLED;
let expected = parser.parse(url, html.to_owned());
let actual = live.snapshot_parser_stream_document();
@@ -3499,7 +3511,7 @@ fn parser_stream_async_prefetch_uses_shared_script_type_classification() {
);
let url = Url::parse("https://example.test/").expect("test url");
- let mut live = crate::DocumentStream::new_parser_stream_for_testing(url);
+ let mut live = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);
for chunk in html_chunks(html) {
live.feed(chunk);
}
@@ -3536,7 +3548,7 @@ fn parser_stream_discovers_modulepreload_link_candidates() {
);
let url = Url::parse("https://example.test/").expect("test url");
- let mut live = crate::DocumentStream::new_parser_stream_for_testing(url);
+ let mut live = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);
let mut modulepreload_candidates = Vec::new();
for chunk in html_chunks(html) {
let outcome = live.pump_parser_step(chunk);
@@ -3570,11 +3582,12 @@ fn parser_stream_discovers_modulepreload_link_candidates() {
fn parser_stream_html_tree_sink_target_matches_parser_for_parser_created_flag() {
let html = "<!doctype html><html><body><script src=\"/app.js\"></script><style>@import url('/a.css');</style></body></html>";
let url = Url::parse("https://example.test/").expect("test url");
- let mut live = crate::DocumentStream::new_parser_stream_for_testing(url.clone());
+ let mut live =
+ crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url.clone());
for chunk in html_chunks(html) {
live.feed(chunk);
}
- let parser = crate::HtmlParser;
+ let parser = crate::HtmlParser::SCRIPTING_ENABLED;
let expected = parser.parse(url, html.to_owned());
let actual = live.snapshot_parser_stream_document();
@@ -3595,7 +3608,7 @@ fn parser_stream_html_tree_sink_target_matches_parser_for_parser_created_flag()
#[test]
fn parser_stream_runtime_dom_sinks_pump_preserves_runtime_mutation_effects() {
let url = Url::parse("https://example.test/").expect("test url");
- let mut stream = crate::DocumentStream::new_parser_stream_for_testing(url);
+ let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);
let mut dom_host = stream.take_parser_stream_dom_host();
let ptr = &mut dom_host as *mut DomHost;
let mut effects = DomMutationEffects::default();
@@ -3634,7 +3647,7 @@ fn parser_stream_runtime_dom_sinks_pump_preserves_runtime_mutation_effects() {
#[test]
fn parser_stream_runtime_dom_consumer_is_cleared_when_pump_unwinds() {
let url = Url::parse("https://example.test/").expect("test url");
- let mut stream = crate::DocumentStream::new_parser_stream_for_testing(url);
+ let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);
let mut dom_host = stream.take_parser_stream_dom_host();
let ptr = &mut dom_host as *mut DomHost;
let mut effects = DomMutationEffects::default();
@@ -3731,7 +3744,7 @@ fn parser_stream_runtime_dom_sinks_routes_parser_state_writes_through_sink() {
#[test]
fn parser_stream_runtime_dom_sinks_routes_declarative_shadow_attach_through_sink() {
let url = Url::parse("https://example.test/").expect("test url");
- let mut stream = crate::DocumentStream::new_parser_stream_for_testing(url);
+ let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);
let mut dom_host = stream.take_parser_stream_dom_host();
let ptr = &mut dom_host as *mut DomHost;
let mut effects = DomMutationEffects::default();
@@ -3823,7 +3836,7 @@ fn parser_stream_runtime_dom_sinks_routes_tree_adjacency_reads_through_sink() {
#[test]
fn parser_stream_runtime_dom_sinks_routes_script_planning_reads_through_sink() {
let url = Url::parse("https://example.test/").expect("test url");
- let mut stream = crate::DocumentStream::new_parser_stream_for_testing(url);
+ let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);
let mut dom_host = stream.take_parser_stream_dom_host();
let ptr = &mut dom_host as *mut DomHost;
let mut effects = DomMutationEffects::default();
@@ -3887,7 +3900,7 @@ fn parser_stream_runtime_dom_sinks_routes_script_planning_reads_through_sink() {
#[test]
fn parser_stream_runtime_dom_sinks_routes_stylesheet_blocking_reads_through_sink() {
let url = Url::parse("https://example.test/").expect("test url");
- let mut stream = crate::DocumentStream::new_parser_stream_for_testing(url);
+ let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);
let mut dom_host = stream.take_parser_stream_dom_host();
let ptr = &mut dom_host as *mut DomHost;
let mut effects = DomMutationEffects::default();
@@ -3934,8 +3947,10 @@ fn parser_stream_live_document_root_writes_detached_document() {
let child_document = dom_host.create_detached_html_document_with_url(child_url.clone());
let ptr = &mut dom_host as *mut DomHost;
let mut effects = DomMutationEffects::default();
- let mut stream =
- crate::DocumentStream::new_live_document_root_for_testing(child_url, child_document);
+ let mut stream = crate::DocumentStream::new_scripting_enabled_live_document_root_for_testing(
+ child_url,
+ child_document,
+ );
{
let mut collector = TestMutationEffectCollector {
@@ -3998,6 +4013,7 @@ fn parser_stream_live_fragment_root_writes_fragment() {
"div",
&mut collector,
false,
+ true,
);
let _ = stream.pump_parser_step_with_runtime_dom_consumer_without_element_creation(
"<span id='frag'>fragment text</span>",
@@ -4048,7 +4064,7 @@ fn parser_stream_live_fragment_root_writes_fragment() {
#[test]
fn parser_stream_element_creation_sink_can_own_token_attributes() {
let url = Url::parse("https://example.test/").expect("test url");
- let mut stream = crate::DocumentStream::new_parser_stream_for_testing(url);
+ let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);
let mut dom_host = stream.take_parser_stream_dom_host();
let ptr = &mut dom_host as *mut DomHost;
let mut effects = DomMutationEffects::default();
@@ -4094,7 +4110,7 @@ fn parser_stream_element_creation_sink_can_own_token_attributes() {
#[test]
fn parser_stream_element_creation_request_reports_intended_parent() {
let url = Url::parse("https://example.test/").expect("test url");
- let mut stream = crate::DocumentStream::new_parser_stream_for_testing(url);
+ let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);
let mut dom_host = stream.take_parser_stream_dom_host();
let document = dom_host.document_handle();
let ptr = &mut dom_host as *mut DomHost;
@@ -4181,8 +4197,10 @@ fn parser_stream_element_creation_sink_uses_live_document_root_handle() {
let child_document = dom_host.create_detached_html_document_with_url(child_url.clone());
let ptr = &mut dom_host as *mut DomHost;
let mut effects = DomMutationEffects::default();
- let mut stream =
- crate::DocumentStream::new_live_document_root_for_testing(child_url, child_document);
+ let mut stream = crate::DocumentStream::new_scripting_enabled_live_document_root_for_testing(
+ child_url,
+ child_document,
+ );
let mut element_creation = TestElementCreationCollector {
dom_host: ptr,
created_handle: None,
@@ -4220,7 +4238,7 @@ fn parser_stream_element_creation_sink_uses_live_document_root_handle() {
#[test]
fn parser_stream_owned_bootstrap_builds_dom_without_mutation_owner() {
let url = Url::parse("https://example.test/").expect("test url");
- let mut stream = crate::DocumentStream::new_parser_stream_for_testing(url);
+ let mut stream = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);
stream.feed(
"<!doctype html><html><body><div id='a'></div><script src='/app.js'></script></body></html>",
@@ -4244,7 +4262,7 @@ fn parser_stream_owned_bootstrap_builds_dom_without_mutation_owner() {
fn parser_stream_does_not_prefetch_whitespace_type_async_script() {
let html = "<!doctype html><html><head><script async src=\"/data.js\" type=\" \"></script></head><body></body></html>";
let url = Url::parse("https://example.test/").expect("test url");
- let mut live = crate::DocumentStream::new_parser_stream_for_testing(url);
+ let mut live = crate::DocumentStream::new_scripting_enabled_parser_stream_for_testing(url);
for chunk in html_chunks(html) {
live.feed(chunk);
}
diff --git a/moli-parser/src/script_planning.rs b/moli-parser/src/script_planning.rs
index 886c53279..c5f33ca91 100644
--- a/moli-parser/src/script_planning.rs
+++ b/moli-parser/src/script_planning.rs
@@ -589,7 +589,7 @@ mod tests {
#[test]
fn parser_script_classification_uses_language_when_type_is_absent() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.test/").unwrap(),
"<!doctype html><script language='javascript'>ok()</script><script language=' javascript '>bad()</script>".to_owned(),
);
@@ -611,7 +611,7 @@ mod tests {
#[test]
fn parser_script_classification_applies_legacy_for_event_gate() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.test/").unwrap(),
"<!doctype html><script for=' window ' event=' onload() '>ok()</script><script for='window' event='onclick'>bad()</script>".to_owned(),
);
@@ -632,7 +632,7 @@ mod tests {
#[test]
fn parser_script_classification_applies_nomodule_only_to_classic_scripts() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.test/").unwrap(),
"<!doctype html><script nomodule>legacy()</script><script nomodule type='module'>modern()</script>"
.to_owned(),
@@ -655,7 +655,7 @@ mod tests {
#[test]
fn parser_svg_script_ignores_html_only_classification_and_scheduling_attributes() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.test/").unwrap(),
"<!doctype html><svg><script nomodule defer language='application/json' for='not-window' event='onclick' href='/svg.js'></script></svg>"
.to_owned(),
@@ -678,7 +678,7 @@ mod tests {
#[test]
fn empty_external_script_src_is_not_resolved_to_document_url() {
let final_url = Url::parse("https://example.test/page.html").unwrap();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
final_url.clone(),
"<!doctype html><script src=\"\"></script>".to_owned(),
);
@@ -700,7 +700,7 @@ mod tests {
#[test]
fn parser_script_source_uses_direct_text_children_only() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.test/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -724,7 +724,7 @@ mod tests {
#[test]
fn external_script_src_resolves_against_document_base_url() {
let final_url = Url::parse("https://example.test/fetch-src/alpha/base.html").unwrap();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
final_url.clone(),
"<!doctype html><base href=\"../beta/\"><script src=\"test.js\"></script>".to_owned(),
);
diff --git a/moli-parser/src/session.rs b/moli-parser/src/session.rs
index 7e15581e0..7a06aee4c 100644
--- a/moli-parser/src/session.rs
+++ b/moli-parser/src/session.rs
@@ -1,7 +1,10 @@
+#[cfg(any(test, feature = "test-support"))]
use std::rc::Rc;
+#[cfg(any(test, feature = "test-support"))]
+use html5ever::{LocalName, Namespace, QualName};
use html5ever::{
- LocalName, Namespace, ParseOpts, QualName,
+ ParseOpts,
tendril::StrTendril,
tokenizer::{
BufferQueue, TagKind, Token, TokenSink, TokenSinkResult, Tokenizer, TokenizerOpts,
@@ -9,6 +12,7 @@ use html5ever::{
tree_builder::{TreeBuilder, TreeBuilderOpts, TreeSink},
};
use markup5ever::TokenizerResult;
+#[cfg(any(test, feature = "test-support"))]
use moli_dom::native::NativeNodeId;
use super::{
@@ -306,9 +310,10 @@ fn feed_with_definitive_encoding(
pub(super) fn new_html_tree_sink_session(
target: ParserStreamHtmlTreeSinkTarget,
+ scripting_enabled: bool,
) -> HtmlTreeSinkSession {
let sink = DocumentSink::new(target);
- let parser = HtmlParserSession::new(sink, html_parse_opts());
+ let parser = HtmlParserSession::new(sink, html_parse_opts_with_scripting(scripting_enabled));
let script_input = ParserInputQueue::default();
HtmlTreeSinkSession {
@@ -317,11 +322,13 @@ pub(super) fn new_html_tree_sink_session(
}
}
+#[cfg(any(test, feature = "test-support"))]
pub(super) fn new_fragment_html_tree_sink_session(
target: ParserStreamHtmlTreeSinkTarget,
context_handle: NativeNodeId,
context_namespace: &str,
context_local_name: &str,
+ scripting_enabled: bool,
) -> HtmlTreeSinkSession {
let sink = DocumentSink::new(target);
let context = QualName::new(
@@ -330,7 +337,12 @@ pub(super) fn new_fragment_html_tree_sink_session(
LocalName::from(context_local_name),
);
let context_handle = ParseHandle::new(context_handle, Some(Rc::new(context)));
- let parser = HtmlParserSession::new_fragment(sink, html_parse_opts(), context_handle, true);
+ let parser = HtmlParserSession::new_fragment(
+ sink,
+ html_parse_opts_with_scripting(scripting_enabled),
+ context_handle,
+ scripting_enabled,
+ );
let script_input = ParserInputQueue::default();
HtmlTreeSinkSession {
@@ -339,10 +351,6 @@ pub(super) fn new_fragment_html_tree_sink_session(
}
}
-pub(super) fn html_parse_opts() -> ParseOpts {
- html_parse_opts_with_scripting(true)
-}
-
pub(super) fn html_parse_opts_with_scripting(scripting_enabled: bool) -> ParseOpts {
ParseOpts {
tree_builder: TreeBuilderOpts {
diff --git a/moli-parser/src/stream.rs b/moli-parser/src/stream.rs
index d94e9f2c4..6eb4516fa 100644
--- a/moli-parser/src/stream.rs
+++ b/moli-parser/src/stream.rs
@@ -17,6 +17,8 @@ use crate::script_planning::{
classify_parser_script,
};
+#[cfg(any(test, feature = "test-support"))]
+use super::session::new_fragment_html_tree_sink_session;
use super::{
html::{
ParserBlockingStylesheetPause, ParserFinishDiscoverySignals, ParserInputQueue,
@@ -25,10 +27,7 @@ use super::{
ParserYield,
},
live_target::{ParserRuntimeDomSinks, ParserStreamHtmlTreeSinkTarget},
- session::{
- HtmlParserSession, HtmlParserSessionResult, new_fragment_html_tree_sink_session,
- new_html_tree_sink_session,
- },
+ session::{HtmlParserSession, HtmlParserSessionResult, new_html_tree_sink_session},
};
pub(super) struct HtmlTreeSinkStream {
@@ -425,8 +424,11 @@ pub(crate) fn prepare_parser_script_handoff_for_static_document(
}
impl HtmlTreeSinkStream {
- pub(super) fn from_target(target: ParserStreamHtmlTreeSinkTarget) -> Self {
- let session = new_html_tree_sink_session(target);
+ pub(super) fn from_target_with_scripting(
+ target: ParserStreamHtmlTreeSinkTarget,
+ scripting_enabled: bool,
+ ) -> Self {
+ let session = new_html_tree_sink_session(target, scripting_enabled);
Self {
parser: session.parser,
script_input: session.script_input,
@@ -435,17 +437,20 @@ impl HtmlTreeSinkStream {
}
}
+ #[cfg(any(test, feature = "test-support"))]
pub(super) fn from_fragment_target(
target: ParserStreamHtmlTreeSinkTarget,
context_handle: NativeNodeId,
context_namespace: &str,
context_local_name: &str,
+ scripting_enabled: bool,
) -> Self {
let session = new_fragment_html_tree_sink_session(
target,
context_handle,
context_namespace,
context_local_name,
+ scripting_enabled,
);
Self {
parser: session.parser,
@@ -1158,7 +1163,7 @@ mod tests {
}
fn first_script_handle(html: &str) -> (NativeDom, NativeNodeId) {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/").expect("test url should parse"),
html.to_owned(),
@@ -1243,7 +1248,7 @@ mod tests {
#[test]
fn parser_stream_feed_continues_past_definitive_encoding_indicator() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1261,7 +1266,7 @@ mod tests {
#[test]
fn parser_stream_pump_continues_past_definitive_encoding_indicator() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1281,7 +1286,7 @@ mod tests {
#[test]
fn parser_stream_finish_continues_past_definitive_encoding_indicator() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
let outcome = stream.pump_parser_step(concat!(
@@ -1439,7 +1444,7 @@ mod tests {
#[test]
fn parser_handoff_preserves_defer_modes_for_owner_acceptance() {
- let mut classic_stream = DocumentStream::new_parser_stream_for_testing(
+ let mut classic_stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
let classic = classic_stream
@@ -1454,7 +1459,7 @@ mod tests {
assert_eq!(script.kind, ScriptKind::Classic);
assert_eq!(script.mode, ScriptMode::Defer);
- let mut module_stream = DocumentStream::new_parser_stream_for_testing(
+ let mut module_stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
let module = module_stream
@@ -1472,7 +1477,7 @@ mod tests {
#[test]
fn parser_stream_assigns_stable_positions_to_shadow_root_scripts() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
let first = stream
@@ -1506,7 +1511,7 @@ mod tests {
#[test]
fn parser_stream_keeps_ordinary_template_scripts_inert() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
let handoff = stream
@@ -1541,7 +1546,7 @@ mod tests {
#[test]
fn parser_handoff_keeps_import_maps_out_of_executable_script_lanes() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
let result = stream
@@ -1561,7 +1566,7 @@ mod tests {
if source.contains("\"x\":\"/x.js\"")
));
- let mut external_stream = DocumentStream::new_parser_stream_for_testing(
+ let mut external_stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
let result = external_stream
@@ -1621,7 +1626,7 @@ mod tests {
#[test]
fn empty_src_parser_script_handoff_is_unprepared_not_fetchable() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1646,7 +1651,7 @@ mod tests {
#[test]
fn invalid_src_parser_script_handoff_preserves_preparation_failure() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1674,7 +1679,7 @@ mod tests {
#[test]
fn parser_script_handoff_uses_html5ever_line_with_unknown_column_across_input_chunks() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1699,7 +1704,7 @@ mod tests {
#[test]
fn nonempty_parser_inserted_input_permanently_degrades_source_locations() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1746,7 +1751,7 @@ mod tests {
#[test]
fn blocked_nested_writes_keep_each_input_at_its_insertion_depth() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1772,7 +1777,7 @@ mod tests {
#[test]
fn parser_token_crossing_inserted_and_original_input_stays_unknown() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1819,7 +1824,7 @@ mod tests {
#[test]
fn parser_inserted_character_reference_chunks_degrade_without_disrupting_parsing() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
let markup =
@@ -1852,7 +1857,7 @@ mod tests {
#[test]
fn parser_original_source_uses_html5ever_line_without_tracking_utf16_columns() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1874,7 +1879,7 @@ mod tests {
#[test]
fn empty_parser_inserted_input_preserves_following_line_location() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1906,7 +1911,7 @@ mod tests {
#[test]
fn parser_stream_surfaces_inline_svg_script_handoff() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1944,7 +1949,7 @@ mod tests {
#[test]
fn parser_stream_surfaces_self_closing_external_svg_script_handoff() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1971,7 +1976,7 @@ mod tests {
#[test]
fn parser_stream_does_not_execute_svg_script_popped_by_an_ancestor_end_tag() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -1992,7 +1997,7 @@ mod tests {
#[test]
fn data_block_handoff_consumes_parser_inserted_prepare_state() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -2024,7 +2029,7 @@ mod tests {
#[test]
fn parser_stream_records_custom_element_construction_handoff_candidates() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
stream.note_defined_autonomous_custom_element("x-ready");
@@ -2065,7 +2070,7 @@ mod tests {
#[test]
fn parser_stream_surfaces_multiple_custom_element_handoffs_one_at_a_time() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
stream.note_defined_autonomous_custom_element("x-ready");
@@ -2108,7 +2113,7 @@ mod tests {
#[test]
fn parser_stream_custom_element_handoff_pauses_before_following_sibling_tokens() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
stream.note_defined_autonomous_custom_element("x-ready");
@@ -2139,7 +2144,7 @@ mod tests {
#[test]
fn parser_stream_consumes_blocking_stylesheet_pause_before_resuming_tokenizer() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -2193,7 +2198,7 @@ mod tests {
#[test]
fn parser_stream_feed_consumes_custom_element_handoff_without_runtime_owner() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
stream.note_defined_autonomous_custom_element("x-ready");
@@ -2225,7 +2230,7 @@ mod tests {
#[test]
fn parser_stream_does_not_record_custom_element_handoff_without_runtime_definition() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page.html").expect("test url"),
);
@@ -2282,7 +2287,8 @@ mod tests {
#[test]
fn parser_stream_caches_document_url_before_runtime_dom_takeover() {
let url = Url::parse("https://example.test/page.html").expect("test url");
- let mut stream = DocumentStream::new_parser_stream_for_testing(url.clone());
+ let mut stream =
+ DocumentStream::new_scripting_enabled_parser_stream_for_testing(url.clone());
let dom_host = stream.take_parser_stream_dom_host();
let cached_url = stream.with_stylesheet_blocking_read_view(|view| view.final_url_clone());
@@ -2297,7 +2303,7 @@ mod tests {
#[test]
fn parser_stream_reports_style_import_blocker_before_classic_handoff() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page").expect("test url"),
);
@@ -2328,7 +2334,7 @@ mod tests {
#[test]
fn parser_stream_reports_split_connected_meta_csp_once_and_ignores_template_contents() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page").expect("test url"),
);
@@ -2362,7 +2368,7 @@ mod tests {
#[test]
fn parser_stream_reports_style_import_blocker_on_runtime_dom_sinks() {
- let mut stream = DocumentStream::new_parser_stream_for_testing(
+ let mut stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
Url::parse("https://example.test/page").expect("test url"),
);
let mut dom_host = stream.take_parser_stream_dom_host();
diff --git a/moli-parser/src/stylesheet_blocking.rs b/moli-parser/src/stylesheet_blocking.rs
index 4aefcae94..44b704975 100644
--- a/moli-parser/src/stylesheet_blocking.rs
+++ b/moli-parser/src/stylesheet_blocking.rs
@@ -67,7 +67,7 @@ mod tests {
#[test]
fn document_owned_blocking_candidates_include_parser_created_style_imports() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
url::Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><style>@import url('/slow.css');</style><script defer>window.x = 1;</script></head></html>".to_owned(),
@@ -94,7 +94,7 @@ mod tests {
#[test]
fn parser_created_link_blocker_is_captured_before_link_processing_state_is_consumed() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let mut stream = parser.start_document(url::Url::parse("https://example.com/").unwrap());
stream.append_to_end(
"<!doctype html><html><head><link rel=stylesheet href='/slow.css'><script>window.x = 1;</script></head></html>".to_owned(),
@@ -132,7 +132,7 @@ mod tests {
#[test]
fn stylesheet_link_resolves_against_the_processed_document_base_url() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
url::Url::parse("https://example.com/page/index.html").unwrap(),
"<!doctype html><html><head><base href=\"/assets/\"><link rel=\"stylesheet\" href=\"app.css\"></head></html>"
@@ -196,7 +196,7 @@ mod tests {
#[test]
fn connected_preload_like_link_url_accepts_prefetch() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
url::Url::parse("https://example.com/path/page.html").unwrap(),
"<!doctype html><html><head><link rel=\"prefetch\" href=\"../next.html\"></head><body></body></html>"
@@ -223,7 +223,7 @@ mod tests {
#[test]
fn connected_preload_like_link_url_accepts_compression_dictionary() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
url::Url::parse("https://example.com/path/page.html").unwrap(),
"<!doctype html><html><head><link rel=\"compression-dictionary\" href=\"../dict.bin\"></head><body></body></html>"
diff --git a/moli-renderer-v8/Cargo.toml b/moli-renderer-v8/Cargo.toml
index 26d2f1235..5ba9ecc5a 100644
--- a/moli-renderer-v8/Cargo.toml
+++ b/moli-renderer-v8/Cargo.toml
@@ -108,6 +108,7 @@ wasm_dep_analyzer = { git = "https://github.com/ldm0/wasm_dep_analyzer", branch
[dev-dependencies]
moli-fetch = { path = "../moli-fetch", features = ["test-support"] }
+moli-parser = { path = "../moli-parser", features = ["test-support"] }
moli-page-types = { path = "../moli-page-types", features = ["test-support"] }
moli-v8-test-util = { path = "../moli-v8-test-util" }
moli-websocket = { path = "../moli-websocket", features = ["test-support"] }
diff --git a/moli-renderer-v8/src/context_bootstrap/range_algorithms/tree_ops.rs b/moli-renderer-v8/src/context_bootstrap/range_algorithms/tree_ops.rs
index b29c7d592..bb22233ee 100644
--- a/moli-renderer-v8/src/context_bootstrap/range_algorithms/tree_ops.rs
+++ b/moli-renderer-v8/src/context_bootstrap/range_algorithms/tree_ops.rs
@@ -15,14 +15,12 @@ pub(in crate::context_bootstrap) fn create_contextual_fragment_internal<'s>(
return create_detached_contextual_fragment(scope, document, html);
};
let document_handle = range_tree_op_node_handle(scope, host_ptr, document)?;
- let scripting_enabled = runtime.document_scripting_enabled(document_handle);
let fragment = runtime.build_range_contextual_fragment_from_html(
scope,
host_ptr,
document_handle,
context_handle,
html,
- scripting_enabled,
)?;
runtime
.native_bridge_mut()
diff --git a/moli-renderer-v8/src/document_runtime.rs b/moli-renderer-v8/src/document_runtime.rs
index 0d1957ed8..c0cb02df6 100644
--- a/moli-renderer-v8/src/document_runtime.rs
+++ b/moli-renderer-v8/src/document_runtime.rs
@@ -1368,7 +1368,7 @@ mod tests {
#[test]
fn live_runtime_dom_host_forwards_the_canonical_document_base_url() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.test/path/page.html").unwrap(),
"<!doctype html><html><head><base href=\"/assets/\"></head></html>".to_owned(),
);
@@ -1391,7 +1391,7 @@ mod tests {
#[test]
fn dom_host_builds_from_parsed_document_and_updates_text_content() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body><main>seed</main></body></html>".to_owned(),
@@ -1412,7 +1412,7 @@ mod tests {
#[test]
fn live_runtime_dom_host_direct_borrow_does_not_block_runtime_access() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body><main>seed</main></body></html>".to_owned(),
@@ -1428,7 +1428,7 @@ mod tests {
#[test]
fn parser_reentry_state_tracks_script_pause_insertion_and_dynamic_markup() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
@@ -1500,7 +1500,7 @@ mod tests {
#[test]
fn structural_mutation_guard_tracks_nested_raw_tree_splices() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
@@ -1531,7 +1531,7 @@ mod tests {
#[test]
fn parser_runtime_dom_owner_allows_nested_steps_on_same_document_incarnation() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body><main>seed</main></body></html>".to_owned(),
@@ -1562,7 +1562,7 @@ mod tests {
#[test]
#[should_panic(expected = "current Document incarnation")]
fn parser_runtime_dom_owner_rejects_document_replacement() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body><main>seed</main></body></html>".to_owned(),
@@ -1576,7 +1576,7 @@ mod tests {
#[test]
fn dom_host_updates_tree_navigation_and_contains_relations() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body><main id=one>one</main><main id=two>two</main></body></html>"
@@ -1647,7 +1647,7 @@ mod tests {
#[test]
fn dom_host_reports_unified_mutation_effects() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
@@ -1699,7 +1699,7 @@ mod tests {
#[test]
fn dom_host_uses_connected_script_roots_only_for_non_script_subtrees() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
@@ -1724,7 +1724,7 @@ mod tests {
#[test]
fn dom_host_scans_connected_shadow_trees_for_scripts() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
@@ -1752,7 +1752,7 @@ mod tests {
#[test]
fn dom_host_flattens_nested_slot_fallback_without_losing_siblings() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
@@ -1795,7 +1795,7 @@ mod tests {
#[test]
fn dom_host_slot_mutation_effects_mark_old_and_new_slots() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
@@ -1839,7 +1839,7 @@ mod tests {
#[test]
fn dom_host_move_effects_mark_shadow_slot_changes() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
@@ -1894,7 +1894,7 @@ mod tests {
#[test]
fn document_runtime_replace_live_document_preserves_shadow_root_bindings() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
@@ -1937,7 +1937,7 @@ mod tests {
#[test]
fn document_runtime_replace_live_document_preserves_script_already_started() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><script src=\"/app.js\"></script></head><body></body></html>"
@@ -1971,7 +1971,7 @@ mod tests {
#[test]
fn document_runtime_can_mark_script_already_started_by_node_id() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><script src=\"/app.js\"></script></head><body></body></html>"
@@ -2001,7 +2001,7 @@ mod tests {
#[test]
fn document_runtime_sets_parser_script_force_async_like_chrome() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><script></script><script async></script></head><body></body></html>"
@@ -2044,7 +2044,7 @@ mod tests {
#[test]
fn document_runtime_snapshot_projects_live_dom_without_reparse() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body><main id=seed>seed</main></body></html>"
@@ -2078,7 +2078,7 @@ mod tests {
#[test]
fn parser_roundtrip_through_live_runtime_keeps_style_import_text_before_later_script() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let mut stream = parser.start_document(Url::parse("https://example.com/").unwrap());
let html = "<!doctype html><html><head><script>window.start = 1;</script><style>@import url('/slow.css');</style><script>window.afterStyle = 1;</script><script src='/blocking.js'></script></head><body><div id='late'>late</div></body></html>";
@@ -2137,7 +2137,7 @@ mod tests {
#[test]
fn parser_roundtrip_after_live_dom_mutation_keeps_later_body_hidden() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let mut stream = parser.start_document(Url::parse("https://example.com/").unwrap());
let html = "<!doctype html><html><head><script>window.start = 1;</script><script>window.after = 1;</script></head><body><div id='late'>late</div></body></html>";
@@ -2189,7 +2189,7 @@ mod tests {
#[test]
fn precedes_in_document_order_handles_disconnected_roots_without_underflow() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body><div id=live></div></body></html>".to_owned(),
@@ -2209,7 +2209,7 @@ mod tests {
#[test]
fn dom_host_import_and_adopt_node_preserve_owner_document_and_parentage() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body><div id=container><span id=seed>seed</span></div></body></html>"
@@ -2252,7 +2252,7 @@ mod tests {
#[test]
fn dom_host_rebuilds_id_lookup_after_id_attribute_mutation() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body><main id=one>one</main><main>two</main></body></html>"
@@ -2275,7 +2275,7 @@ mod tests {
#[test]
fn dom_host_invalidates_live_collection_cache_on_tree_and_attribute_mutations() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body><main></main></body></html>".to_owned(),
@@ -2322,7 +2322,7 @@ mod tests {
#[test]
fn dom_host_normalize_merges_adjacent_text_nodes_recursively() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body><div id=container></div></body></html>".to_owned(),
@@ -2393,7 +2393,7 @@ mod tests {
#[tokio::test]
async fn injected_page_task_can_wake_parse_time_turn_without_timeout_fallback() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
@@ -2494,7 +2494,7 @@ mod tests {
#[tokio::test(flavor = "current_thread")]
async fn response_csp_blocks_ownerless_stylesheet_admission() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/page").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
@@ -2553,7 +2553,7 @@ mod tests {
#[test]
fn stale_connected_stylesheet_network_result_releases_source_owner() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/page").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href=/current.css></head><body></body></html>"
@@ -2593,7 +2593,7 @@ mod tests {
#[tokio::test]
async fn active_link_load_keeps_physical_observation_separate_from_client_terminal() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/page").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href=/current.css></head><body></body></html>"
@@ -2640,7 +2640,7 @@ mod tests {
#[tokio::test]
async fn removed_link_rejects_its_detached_load_network_source_owner() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/page").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href=/current.css></head><body></body></html>"
@@ -2689,7 +2689,7 @@ mod tests {
#[tokio::test]
async fn disabled_link_rejects_its_detached_load_network_source_owner() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/page").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href=/current.css></head><body></body></html>"
@@ -2741,7 +2741,7 @@ mod tests {
#[tokio::test]
async fn same_url_reprocess_rejects_the_detached_owner_bound_load_object() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/page").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href=/a.css></head><body></body></html>"
@@ -2794,7 +2794,7 @@ mod tests {
#[tokio::test]
async fn linked_stylesheet_request_attribute_reprocess_captures_new_fetch_options() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.com/page").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href='http://127.0.0.1:9/a.css' crossorigin=anonymous integrity=sha256-first referrerpolicy=no-referrer fetchpriority=low></head><body></body></html>"
@@ -3031,7 +3031,7 @@ mod tests {
});
let document_url = Url::parse(&format!("http://{addr}/page")).unwrap();
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
document_url.clone(),
"<!doctype html><html><head><style>@import url('/imported.css');</style><script src='/app.js'></script></head><body></body></html>".to_owned(),
@@ -3117,7 +3117,7 @@ mod tests {
});
let document_url = Url::parse(&format!("http://{addr}/page")).unwrap();
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
document_url.clone(),
"<!doctype html><html><head><style>@import url('/imported.css');</style><script src='/app.js'></script></head><body></body></html>".to_owned(),
@@ -3214,7 +3214,7 @@ mod tests {
});
let document_url = Url::parse(&format!("http://{addr}/page")).unwrap();
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
document_url.clone(),
"<!doctype html><html><head><style>@import url('/missing.css');</style></head><body></body></html>"
@@ -3288,7 +3288,7 @@ mod tests {
#[test]
fn drained_preload_like_network_result_still_drives_load_event_result() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document_url = Url::parse("https://example.com/page").unwrap();
let request_url = Url::parse("https://example.com/chunk.js").unwrap();
let document = parser.parse(
@@ -3361,7 +3361,7 @@ mod tests {
#[test]
fn same_parameter_connected_completion_cannot_cross_operation_identity() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document_url = Url::parse("https://example.com/page").unwrap();
let request_url = Url::parse("https://example.com/a.css").unwrap();
let document = parser.parse(
@@ -3461,7 +3461,7 @@ mod tests {
#[test]
fn accepted_style_import_result_installs_only_for_its_exact_processing_operation() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document_url = Url::parse("https://example.com/page").unwrap();
let request_url = Url::parse("https://example.com/shared.css").unwrap();
let document = parser.parse(
@@ -3518,7 +3518,7 @@ mod tests {
#[test]
fn accepted_style_import_result_loses_install_authority_after_same_url_aba() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document_url = Url::parse("https://example.com/page").unwrap();
let request_url = Url::parse("https://example.com/shared.css").unwrap();
let document = parser.parse(
diff --git a/moli-renderer-v8/src/document_runtime/document_write.rs b/moli-renderer-v8/src/document_runtime/document_write.rs
index c6356396a..6aa07e8f2 100644
--- a/moli-renderer-v8/src/document_runtime/document_write.rs
+++ b/moli-renderer-v8/src/document_runtime/document_write.rs
@@ -328,6 +328,7 @@ impl DocumentRuntime {
let parser = DocumentParserSession::start_open_live_document(
self.document_url().clone(),
self.document_handle(),
+ self.document_scripting_enabled(),
);
self.root_document_parser = Some(parser);
}
@@ -608,7 +609,7 @@ impl DocumentRuntime {
scripting_enabled: bool,
) -> Option<DomHandle> {
let first_node_index = self.dom_host().dom().len();
- let parser = HtmlParser;
+ let parser = HtmlParser::with_scripting_enabled(scripting_enabled);
let context_node = self.dom_host().node(context_handle);
let context_namespace = context_node
.and_then(Node::namespace)
@@ -624,12 +625,11 @@ impl DocumentRuntime {
{
context_local_name = "body".to_owned();
}
- let parsed = parser.parse_fragment_without_declarative_shadow_roots_with_scripting(
+ let parsed = parser.parse_fragment_without_declarative_shadow_roots(
self.document_url().clone(),
&context_namespace,
&context_local_name,
html.to_owned(),
- scripting_enabled,
);
let is_frameset_context = context_namespace == "http://www.w3.org/1999/xhtml"
&& context_local_name.eq_ignore_ascii_case("frameset");
@@ -705,8 +705,8 @@ impl DocumentRuntime {
document_handle: DomHandle,
context_handle: DomHandle,
html: &str,
- scripting_enabled: bool,
) -> Option<DomHandle> {
+ let scripting_enabled = unsafe { &*host_ptr }.document_scripting_enabled(document_handle);
self.build_fragment_from_html_with_context_mode(
scope,
host_ptr,
@@ -730,6 +730,7 @@ impl DocumentRuntime {
scripts_already_started: bool,
custom_element_upgrade_timing: HtmlFragmentCustomElementUpgradeTiming,
) -> Option<DomHandle> {
+ let scripting_enabled = unsafe { &*host_ptr }.document_scripting_enabled(document_handle);
self.build_fragment_from_html_with_context_mode(
scope,
host_ptr,
@@ -739,7 +740,7 @@ impl DocumentRuntime {
scripts_already_started,
custom_element_upgrade_timing,
HtmlFragmentParserContextMode::Standard,
- true,
+ scripting_enabled,
)
}
@@ -753,7 +754,8 @@ impl DocumentRuntime {
custom_element_upgrade_timing: HtmlFragmentCustomElementUpgradeTiming,
) -> Option<DomHandle> {
let first_node_index = self.dom_host().dom().len();
- let parser = HtmlParser;
+ let scripting_enabled = unsafe { &*host_ptr }.document_scripting_enabled(document_handle);
+ let parser = HtmlParser::with_scripting_enabled(scripting_enabled);
let context_node = self.dom_host().node(context_handle);
let context_namespace = context_node
.and_then(Node::namespace)
@@ -2751,7 +2753,8 @@ mod tests {
#[test]
fn root_document_parser_is_owned_by_shared_open_session() {
let document_url = Url::parse("https://document-write.test/root-owner.html").unwrap();
- let document = HtmlParser.parse(document_url, "<!doctype html>".to_owned());
+ let document =
+ HtmlParser::SCRIPTING_ENABLED.parse(document_url, "<!doctype html>".to_owned());
let mut runtime = DocumentRuntime::new(&document);
runtime.start_root_document_parser_stream();
@@ -2772,7 +2775,8 @@ mod tests {
#[should_panic(expected = "document.write external-script load id space exhausted")]
fn document_write_external_script_load_ids_never_wrap() {
let document_url = Url::parse("https://document-write.test/load-id.html").unwrap();
- let document = HtmlParser.parse(document_url, "<!doctype html>".to_owned());
+ let document =
+ HtmlParser::SCRIPTING_ENABLED.parse(document_url, "<!doctype html>".to_owned());
let mut runtime = DocumentRuntime::new(&document);
runtime.next_document_write_external_script_load_id = u64::MAX;
@@ -2797,7 +2801,8 @@ mod tests {
.enumerate()
{
let document_url = Url::parse("https://document-write.test/page.html").unwrap();
- let document = HtmlParser.parse(document_url.clone(), html.to_owned());
+ let document =
+ HtmlParser::SCRIPTING_ENABLED.parse(document_url.clone(), html.to_owned());
let node = document.script_handles()[0];
let mut runtime = DocumentRuntime::new(&document);
let script = prepared_script(node, kind, mode, document_url);
diff --git a/moli-renderer-v8/src/document_runtime/dom_facade.rs b/moli-renderer-v8/src/document_runtime/dom_facade.rs
index 47fb82189..08d1e4e74 100644
--- a/moli-renderer-v8/src/document_runtime/dom_facade.rs
+++ b/moli-renderer-v8/src/document_runtime/dom_facade.rs
@@ -892,7 +892,7 @@ mod tests {
use crate::dom::native::DomStylesheetOwnerChangeKind;
fn runtime_with_body() -> (DocumentRuntime, DomHandle) {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
diff --git a/moli-renderer-v8/src/document_runtime/lifecycle.rs b/moli-renderer-v8/src/document_runtime/lifecycle.rs
index 7b1177b30..9efb963de 100644
--- a/moli-renderer-v8/src/document_runtime/lifecycle.rs
+++ b/moli-renderer-v8/src/document_runtime/lifecycle.rs
@@ -625,11 +625,13 @@ mod tests {
#[test]
fn parser_insertion_context_does_not_require_current_script() {
let url = Url::parse("https://example.com/").unwrap();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><body></body></html>".to_owned(),
);
- let stream = Rc::new(RefCell::new(HtmlParser.start_document(url)));
+ let stream = Rc::new(RefCell::new(
+ HtmlParser::SCRIPTING_ENABLED.start_document(url),
+ ));
let mut runtime = DocumentRuntime::new(&document);
runtime.set_current_script_context(CurrentScriptContextSpec {
@@ -753,7 +755,7 @@ mod tests {
#[test]
fn runtime_binding_queue_is_drained_once() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -777,7 +779,7 @@ mod tests {
#[test]
fn document_replacement_parser_blocker_tracks_the_actual_input_stream() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -800,7 +802,7 @@ mod tests {
#[test]
fn parser_discovered_modulepreloads_use_as_module_type_for_keys() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/pages/index.html").unwrap(),
concat!(
"<!doctype html><html><head>",
@@ -888,7 +890,7 @@ mod tests {
#[test]
fn parser_discovered_modulepreload_as_values_match_wpt_matrix() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/pages/index.html").unwrap(),
modulepreload_as_matrix_markup("https://cdn.example/assets/"),
);
@@ -945,7 +947,7 @@ mod tests {
#[test]
fn parser_discovered_modulepreload_invalid_as_warns_each_link_once() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/pages/index.html").unwrap(),
concat!(
"<!doctype html><html><head>",
@@ -1032,7 +1034,7 @@ mod tests {
#[test]
fn parser_discovered_modulepreloads_ignore_fetchpriority_hint() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/pages/index.html").unwrap(),
concat!(
"<!doctype html><html><head>",
@@ -1063,7 +1065,7 @@ mod tests {
#[test]
fn parser_discovered_modulepreloads_skip_non_matching_media() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/pages/index.html").unwrap(),
concat!(
"<!doctype html><html><head>",
@@ -1109,7 +1111,7 @@ mod tests {
#[test]
fn parser_discovered_images_mark_first_five_non_small_priority_boost_candidates() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/pages/index.html").unwrap(),
concat!(
"<!doctype html><html><body>",
@@ -1171,7 +1173,7 @@ mod tests {
#[tokio::test]
async fn domcontentloaded_overtakes_pending_connected_style_load() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href='/app.css'></head><body></body></html>"
.to_owned(),
@@ -1209,7 +1211,7 @@ mod tests {
#[test]
fn parse_time_lifecycle_page_task_materializes_as_page_owned_work() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
);
@@ -1227,7 +1229,7 @@ mod tests {
#[test]
fn ready_document_processing_wake_allows_domcontentloaded_past_pending_connected_style_load() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href='/app.css'></head><body></body></html>"
.to_owned(),
@@ -1258,7 +1260,7 @@ mod tests {
#[test]
fn parse_time_pending_processing_ignores_pending_connected_style_load() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href='/app.css'></head><body></body></html>"
.to_owned(),
@@ -1288,7 +1290,7 @@ mod tests {
#[test]
fn pending_connected_style_queue_is_not_window_load_readiness_fact_source() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href='/app.css'></head><body></body></html>"
.to_owned(),
@@ -1321,7 +1323,7 @@ mod tests {
#[tokio::test]
async fn domcontentloaded_is_not_blocked_by_post_domcontentloaded_runtime_backlog() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1340,7 +1342,7 @@ mod tests {
#[tokio::test]
async fn post_parse_owner_driver_step_keeps_domcontentloaded_ready_with_runtime_backlog() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1363,7 +1365,7 @@ mod tests {
#[tokio::test]
async fn ready_connected_style_load_does_not_overtake_domcontentloaded() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href='/app.css'></head><body></body></html>"
.to_owned(),
@@ -1416,7 +1418,7 @@ mod tests {
#[tokio::test]
async fn ready_connected_style_load_dispatches_while_defer_source_is_pending() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href='/app.css'></head><body></body></html>"
.to_owned(),
@@ -1468,7 +1470,7 @@ mod tests {
}
#[tokio::test(flavor = "current_thread")]
async fn parser_owned_pre_domcontentloaded_task_waits_behind_defer_like_front() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1497,7 +1499,7 @@ mod tests {
#[tokio::test(flavor = "current_thread")]
async fn post_parse_owner_dispatches_ready_connected_style_before_reporting_script_source_wait()
{
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href='/app.css'></head><body></body></html>"
.to_owned(),
@@ -1554,7 +1556,7 @@ mod tests {
#[test]
fn parser_owned_pre_domcontentloaded_delivery_drains_ahead_of_window_load() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1582,7 +1584,7 @@ mod tests {
#[test]
fn parser_owned_pre_domcontentloaded_delivery_keeps_owner_source_behind_run_record_front() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1623,7 +1625,7 @@ mod tests {
#[test]
fn parser_owned_pre_domcontentloaded_delivery_preserves_owner_order_ahead_of_domcontentloaded()
{
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1656,7 +1658,7 @@ mod tests {
#[test]
fn parser_owned_pre_domcontentloaded_owner_source_drains_when_queue_is_empty() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1680,7 +1682,7 @@ mod tests {
#[tokio::test]
async fn post_parse_owner_driver_step_keeps_non_window_tail_ready_with_runtime_backlog() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1706,7 +1708,7 @@ mod tests {
#[test]
fn parser_owned_pre_domcontentloaded_task_overtakes_other_post_parse_front() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1736,7 +1738,7 @@ mod tests {
#[test]
fn post_parse_page_task_pop_blocker_distinguishes_parser_owned_source_from_window_load_backlog()
{
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1766,7 +1768,7 @@ mod tests {
#[test]
fn post_parse_owner_readiness_keeps_domcontentloaded_unblocked_with_parser_owned_source() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1801,7 +1803,7 @@ mod tests {
#[tokio::test]
async fn post_parse_owner_driver_step_awaits_when_window_load_is_blocked_by_runtime_backlog() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href='/app.css'></head><body></body></html>"
.to_owned(),
diff --git a/moli-renderer-v8/src/document_runtime/meta_refresh.rs b/moli-renderer-v8/src/document_runtime/meta_refresh.rs
index 73e9cb3bb..4d6505b37 100644
--- a/moli-renderer-v8/src/document_runtime/meta_refresh.rs
+++ b/moli-renderer-v8/src/document_runtime/meta_refresh.rs
@@ -538,7 +538,7 @@ mod tests {
#[test]
fn document_runtime_finds_top_level_meta_refresh() {
- let document = crate::parser::HtmlParser.parse(
+ let document = crate::parser::HtmlParser::SCRIPTING_ENABLED.parse(
base_url(),
r#"<!doctype html><head><meta http-equiv="refresh" content="0;redirected.html"></head>"#
.to_owned(),
@@ -556,7 +556,7 @@ mod tests {
#[test]
fn sandbox_without_allow_scripts_blocks_meta_refresh_at_creation_time() {
- let document = crate::parser::HtmlParser.parse(
+ let document = crate::parser::HtmlParser::SCRIPTING_ENABLED.parse(
base_url(),
r#"<!doctype html><head><meta http-equiv="refresh" content="0;redirected.html"></head>"#
.to_owned(),
@@ -576,7 +576,7 @@ mod tests {
#[test]
fn document_runtime_preserves_delayed_top_level_meta_refresh() {
- let document = crate::parser::HtmlParser.parse(
+ let document = crate::parser::HtmlParser::SCRIPTING_ENABLED.parse(
base_url(),
r#"<!doctype html><head><meta http-equiv="refresh" content="1.5;redirected.html"></head>"#
.to_owned(),
diff --git a/moli-renderer-v8/src/document_runtime/parser_modulepreload.rs b/moli-renderer-v8/src/document_runtime/parser_modulepreload.rs
index 1b7233c10..efa5f3af9 100644
--- a/moli-renderer-v8/src/document_runtime/parser_modulepreload.rs
+++ b/moli-renderer-v8/src/document_runtime/parser_modulepreload.rs
@@ -47,6 +47,9 @@ impl DocumentRuntime {
&mut self,
link_handles: impl IntoIterator<Item = DomHandle>,
) -> ParserDiscoveredModulepreloadResult {
+ if !self.document_scripting_enabled() {
+ return ParserDiscoveredModulepreloadResult::default();
+ }
let Some(document_url) = self.dom_host.final_url().cloned() else {
return ParserDiscoveredModulepreloadResult::default();
};
@@ -204,7 +207,7 @@ mod tests {
#[test]
fn parser_modulepreload_candidate_cannot_cross_document_open_replacement() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.test/initial.html").expect("test URL"),
concat!(
"<!doctype html><html><head>",
@@ -242,4 +245,31 @@ mod tests {
"a stale parser candidate must not publish a link terminal into the replacement"
);
}
+
+ #[test]
+ fn parser_modulepreload_is_inert_when_script_execution_is_disabled() {
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
+ Url::parse("https://example.test/page.html").expect("test URL"),
+ concat!(
+ "<!doctype html><html><head>",
+ "<link id='preload' rel='modulepreload' href='/app.mjs'>",
+ "</head><body></body></html>",
+ )
+ .to_owned(),
+ );
+ let mut runtime = DocumentRuntime::new(&document);
+ runtime.set_script_execution_disabled(true);
+ let preload = runtime
+ .dom_host()
+ .element_handle_by_id("preload")
+ .expect("modulepreload link");
+
+ let (requests, warnings, link_error_tasks) = runtime
+ .accept_parser_discovered_modulepreload_links([preload])
+ .into_parts();
+
+ assert!(requests.is_empty());
+ assert!(warnings.is_empty());
+ assert_eq!(link_error_tasks, 0);
+ }
}
diff --git a/moli-renderer-v8/src/document_runtime/runtime_core.rs b/moli-renderer-v8/src/document_runtime/runtime_core.rs
index 6130faf61..730f98202 100644
--- a/moli-renderer-v8/src/document_runtime/runtime_core.rs
+++ b/moli-renderer-v8/src/document_runtime/runtime_core.rs
@@ -271,6 +271,10 @@ impl DocumentRuntime {
self.script_execution_control.is_disabled()
}
+ pub(crate) fn document_scripting_enabled(&self) -> bool {
+ !self.script_execution_disabled() && self.document_sandbox_policy().allows_scripts
+ }
+
pub(crate) fn script_execution_control(
&self,
) -> crate::script_execution_control::RendererScriptExecutionControl {
diff --git a/moli-renderer-v8/src/document_runtime/script_scheduling.rs b/moli-renderer-v8/src/document_runtime/script_scheduling.rs
index 315c49369..dbf2d4296 100644
--- a/moli-renderer-v8/src/document_runtime/script_scheduling.rs
+++ b/moli-renderer-v8/src/document_runtime/script_scheduling.rs
@@ -142,7 +142,7 @@ mod tests {
#[test]
fn enqueue_post_parse_lifecycle_page_owned_work_routes_through_document_runtime_owner() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
);
@@ -206,7 +206,7 @@ mod tests {
#[test]
fn prepare_post_parse_lifecycle_page_owned_work_injects_boundaries_around_trailing_work() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
);
@@ -241,7 +241,7 @@ mod tests {
#[test]
fn prepare_post_parse_lifecycle_page_owned_work_keeps_runtime_async_tail_after_domcontentloaded()
{
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
);
@@ -426,7 +426,7 @@ mod tests {
#[test]
fn stale_parser_deferred_marker_without_owned_queue_cannot_block_dcl() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body></body></html>".to_owned(),
);
@@ -476,7 +476,7 @@ mod tests {
#[test]
fn document_write_owned_handle_binding_uses_document_write_source() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><script src='/written.js'></script></head><body></body></html>"
.to_owned(),
@@ -512,7 +512,7 @@ mod tests {
#[test]
fn inline_script_load_policy_does_not_require_a_host_handle() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><script>window.inline = true;</script></head><body></body></html>"
.to_owned(),
@@ -533,7 +533,7 @@ mod tests {
#[test]
fn parser_owned_module_failure_planning_uses_explicitly_bound_parser_handle() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><script type='module' src='/app.mjs'></script></head><body></body></html>"
.to_owned(),
@@ -580,7 +580,7 @@ mod tests {
expected = "parser-owned script should bind host handle before failure planning"
)]
fn parser_created_module_failure_planning_production_path_rejects_missing_handle() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><script type='module' src='/app.mjs'></script></head><body></body></html>"
.to_owned(),
@@ -600,7 +600,7 @@ mod tests {
#[test]
fn non_parser_created_module_failure_planning_does_not_synthesize_parser_owned_handle() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -651,7 +651,7 @@ mod tests {
#[test]
fn runtime_owned_in_order_prepared_script_does_not_wait_for_blocking_stylesheets() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -688,7 +688,7 @@ mod tests {
#[test]
fn parser_owned_defer_prepared_script_waits_for_blocking_stylesheets() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -725,7 +725,7 @@ mod tests {
#[test]
fn runtime_owned_in_order_prepared_script_does_not_wait_until_domcontentloaded() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -762,7 +762,7 @@ mod tests {
#[test]
fn runtime_owned_async_prepared_script_does_not_wait_until_domcontentloaded() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -799,7 +799,7 @@ mod tests {
#[test]
fn runtime_owned_module_prepared_script_does_not_wait_until_domcontentloaded() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -837,7 +837,7 @@ mod tests {
#[test]
fn domcontentloaded_state_does_not_reintroduce_runtime_owned_in_order_wait() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -876,7 +876,7 @@ mod tests {
#[test]
fn parser_owned_script_event_planning_resolves_the_preparation_time_handle() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><script src='/missing.js'></script></head><body></body></html>"
.to_owned(),
@@ -896,7 +896,7 @@ mod tests {
#[test]
#[should_panic(expected = "parser-owned handle binding requires a parser-created <script>")]
fn parser_owned_handle_binding_rejects_non_parser_created_script() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
diff --git a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
index 22df7442a..e74af900a 100644
--- a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
+++ b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
@@ -39,7 +39,7 @@ impl DocumentRuntime {
{
return DocumentWriteScriptRunOutcome::Complete;
}
- if self.script_execution_disabled() {
+ if !self.document_scripting_enabled() {
let _ = self.dom_host.set_script_already_started(node, true);
return DocumentWriteScriptRunOutcome::Complete;
}
diff --git a/moli-renderer-v8/src/document_runtime/script_scheduling/script_handles.rs b/moli-renderer-v8/src/document_runtime/script_scheduling/script_handles.rs
index f8d4317d9..364f0336b 100644
--- a/moli-renderer-v8/src/document_runtime/script_scheduling/script_handles.rs
+++ b/moli-renderer-v8/src/document_runtime/script_scheduling/script_handles.rs
@@ -18,7 +18,9 @@ impl DocumentRuntime {
) -> Option<RuntimeScriptStartPlan> {
let options = crate::host::ScriptElementLoaderOptions {
prepare_changed_empty_inline_source: self.requires_trusted_types_for_script(),
- ..crate::host::ScriptElementLoaderOptions::default()
+ ..crate::host::ScriptElementLoaderOptions::with_scripting_enabled(
+ self.document_scripting_enabled(),
+ )
};
plan_script_start(
&mut self.dom_host,
diff --git a/moli-renderer-v8/src/document_runtime/security_policy.rs b/moli-renderer-v8/src/document_runtime/security_policy.rs
index 87c97944b..c894990cc 100644
--- a/moli-renderer-v8/src/document_runtime/security_policy.rs
+++ b/moli-renderer-v8/src/document_runtime/security_policy.rs
@@ -2163,7 +2163,7 @@ mod tests {
fn runtime_for_html(html: &str) -> DocumentRuntime {
let document_url = Url::parse("https://example.test/page").expect("document url");
- let document = HtmlParser.parse(document_url, html.to_owned());
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(document_url, html.to_owned());
DocumentRuntime::from_document(document)
}
diff --git a/moli-renderer-v8/src/document_script_scheduler/page_task_adapter.rs b/moli-renderer-v8/src/document_script_scheduler/page_task_adapter.rs
index f243e3a8a..0ba73438b 100644
--- a/moli-renderer-v8/src/document_script_scheduler/page_task_adapter.rs
+++ b/moli-renderer-v8/src/document_script_scheduler/page_task_adapter.rs
@@ -252,7 +252,7 @@ mod tests {
#[tokio::test]
async fn live_parser_finalization_does_not_rediscover_parser_scripts_from_dom() {
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://post-parse.test/page.html").expect("test url"),
"<!doctype html><script type='module'>export const value = 1;</script>".to_owned(),
);
diff --git a/moli-renderer-v8/src/dom_parser.rs b/moli-renderer-v8/src/dom_parser.rs
index 540bb25f1..5aa5247af 100644
--- a/moli-renderer-v8/src/dom_parser.rs
+++ b/moli-renderer-v8/src/dom_parser.rs
@@ -267,8 +267,8 @@ pub(crate) fn parse_detached_html_document_from_source<'s>(
document_url: Url,
source: &str,
) -> Option<v8::Local<'s, v8::Object>> {
- let parser = HtmlParser;
- let parsed = parser.parse_without_declarative_shadow_roots(document_url, source.to_owned());
+ let parsed = HtmlParser::with_scripting_enabled(false)
+ .parse_without_declarative_shadow_roots(document_url, source.to_owned());
build_detached_document(scope, parsed, DetachedDocumentKind::Html, false)
}
@@ -277,20 +277,27 @@ pub(crate) fn parse_detached_html_document_from_source_with_declarative_shadow_r
document_url: Url,
source: &str,
) -> Option<v8::Local<'s, v8::Object>> {
- let parser = HtmlParser;
- let parsed = parser.parse_dom_host(document_url, source.to_owned());
+ let parsed =
+ HtmlParser::with_scripting_enabled(false).parse_dom_host(document_url, source.to_owned());
build_detached_document_from_dom_host(scope, parsed, DetachedDocumentKind::Html, true)
}
-pub(crate) fn parse_detached_child_document_from_source<'s>(
+/// Builds the DOM projection used for a child browsing-context document.
+///
+/// The projection never executes scripts itself. `html_parser` carries the
+/// target Document's scripting state solely for parser behavior such as
+/// `<noscript>` tokenization; every caller must select that state explicitly.
+pub(crate) fn parse_child_document_projection_from_source<'s>(
scope: &mut v8::PinScope<'s, '_>,
document_url: Url,
source: &str,
content_type: Option<&str>,
character_set: Option<&str>,
+ html_parser: HtmlParser,
) -> Option<v8::Local<'s, v8::Object>> {
let source = preserve_decoded_bom_only_child_body(source, content_type);
- let (parsed, kind) = parse_child_document_snapshot(document_url, &source, content_type);
+ let (parsed, kind) =
+ parse_child_document_snapshot(document_url, &source, content_type, html_parser);
build_detached_document_from_dom_host_with_content_type(
scope,
parsed,
@@ -316,6 +323,7 @@ fn parse_child_document_snapshot(
document_url: Url,
source: &str,
content_type: Option<&str>,
+ html_parser: HtmlParser,
) -> (DomHost, DetachedDocumentKind) {
if content_type.is_some_and(is_dom_parser_xml_mime)
|| child_document_url_is_xml_like(&document_url)
@@ -326,9 +334,8 @@ fn parse_child_document_snapshot(
DetachedDocumentKind::Xml,
);
}
- let parser = HtmlParser;
(
- parser.parse_dom_host(document_url, source.to_owned()),
+ html_parser.parse_dom_host(document_url, source.to_owned()),
DetachedDocumentKind::Html,
)
}
@@ -435,6 +442,7 @@ mod tests {
Url::parse("https://example.test/common/dummy.xml").unwrap(),
"<foo>Dummy XML document</foo>\n",
None,
+ HtmlParser::SCRIPTING_ENABLED,
);
let xml_root = first_document_element(&xml);
assert_eq!(xml_kind, DetachedDocumentKind::Xml);
@@ -448,6 +456,7 @@ mod tests {
r#"<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Dummy XHTML document</title></head><body /></html>
"#,
None,
+ HtmlParser::SCRIPTING_ENABLED,
);
let xhtml_root = first_document_element(&xhtml);
assert_eq!(xhtml_kind, DetachedDocumentKind::Xml);
@@ -460,6 +469,7 @@ mod tests {
Url::parse("https://example.test/common/dummy.html").unwrap(),
"<p>Dummy HTML document</p>\n",
None,
+ HtmlParser::SCRIPTING_ENABLED,
);
let html_root = html.document_element_handle().expect("html root");
assert_eq!(html_kind, DetachedDocumentKind::Html);
@@ -468,4 +478,23 @@ mod tests {
Some("Dummy HTML document\n")
);
}
+
+ #[test]
+ fn child_document_projection_uses_explicit_scripting_mode() {
+ let parse = |parser| {
+ parse_child_document_snapshot(
+ Url::parse("https://example.test/child.html").expect("test URL"),
+ "<noscript><span id='fallback'></span></noscript>",
+ Some("text/html"),
+ parser,
+ )
+ .0
+ };
+
+ let enabled = parse(HtmlParser::SCRIPTING_ENABLED);
+ assert!(enabled.element_handle_by_id("fallback").is_none());
+
+ let disabled = parse(HtmlParser::SCRIPTING_DISABLED);
+ assert!(disabled.element_handle_by_id("fallback").is_some());
+ }
}
diff --git a/moli-renderer-v8/src/host.rs b/moli-renderer-v8/src/host.rs
index 56f47bc17..1d08f5601 100644
--- a/moli-renderer-v8/src/host.rs
+++ b/moli-renderer-v8/src/host.rs
@@ -43,6 +43,7 @@ pub(super) use self::scripts::{
RuntimeScriptStartPlan, RuntimeScriptStartReservation, ScriptElementLoader,
ScriptElementLoaderOptions, ScriptEventKind, ScriptEventTask, ScriptHandleSource,
ScriptPageTaskExecutionKind, apply_parser_script_element_state_transition,
+ apply_parser_script_element_state_without_execution,
begin_prepared_document_write_script_start, build_runtime_prepared_script,
cancel_runtime_script_start_admission, dispatch_script_event,
finish_runtime_script_start_admission, plan_script_start, prepare_runtime_script_start_commit,
diff --git a/moli-renderer-v8/src/host/scripts/loader.rs b/moli-renderer-v8/src/host/scripts/loader.rs
index e5dd77901..1b18d4481 100644
--- a/moli-renderer-v8/src/host/scripts/loader.rs
+++ b/moli-renderer-v8/src/host/scripts/loader.rs
@@ -84,17 +84,33 @@ pub(crate) enum RuntimeScriptStartDecision {
},
}
-#[derive(Debug, Clone, Copy, Default)]
+#[derive(Debug, Clone, Copy)]
pub(crate) struct ScriptElementLoaderOptions {
pub(crate) allow_parser_blocking_modes: bool,
pub(crate) suppress_force_async: bool,
pub(crate) document_write_connected: bool,
+ /// Scripting is disabled for the script element's relevant settings object.
+ /// Valid scripts still commit their already-started state, but they must not
+ /// fetch, register an import map, or execute.
+ pub(crate) scripting_disabled: bool,
/// The caller will apply Trusted Types script-text preparation to the
/// returned inline source, so a changed empty source may still become
/// executable before the HTML empty-source check takes effect.
pub(crate) prepare_changed_empty_inline_source: bool,
}
+impl ScriptElementLoaderOptions {
+ pub(crate) const fn with_scripting_enabled(scripting_enabled: bool) -> Self {
+ Self {
+ allow_parser_blocking_modes: false,
+ suppress_force_async: false,
+ document_write_connected: false,
+ scripting_disabled: !scripting_enabled,
+ prepare_changed_empty_inline_source: false,
+ }
+ }
+}
+
#[derive(Debug, Clone)]
pub(crate) struct PreparedScriptElementStart {
pub(super) preparation: RuntimeScriptPreparationContext,
@@ -322,6 +338,12 @@ pub(crate) fn decide_runtime_script_start(
)),
};
}
+ if options.scripting_disabled {
+ return RuntimeScriptStartDecision::Skip {
+ commit_start: true,
+ reason: Some(ScriptSkipReason::ScriptExecutionDisabled),
+ };
+ }
let source = match script_src {
Some(source) => source,
None => {
@@ -428,6 +450,27 @@ pub(crate) fn apply_parser_script_element_state_transition(
}
}
+pub(crate) fn apply_parser_script_element_state_without_execution(
+ dom_host: &mut DomHost,
+ handoff: &crate::parser::ParserScriptHandoff,
+) {
+ let transition = match handoff {
+ crate::parser::ParserScriptHandoff::NoExecution { outcome, .. } => {
+ outcome.element_state_transition()
+ }
+ crate::parser::ParserScriptHandoff::PreparationFailure { failure, .. } => {
+ failure.element_state_transition()
+ }
+ crate::parser::ParserScriptHandoff::BlockingClassic { .. }
+ | crate::parser::ParserScriptHandoff::AsyncPostParse { .. }
+ | crate::parser::ParserScriptHandoff::NonAsyncPostParse { .. }
+ | crate::parser::ParserScriptHandoff::ImportMap { .. } => {
+ crate::parser::ParserScriptElementStateTransition::MarkAlreadyStarted
+ }
+ };
+ apply_parser_script_element_state_transition(dom_host, handoff.node_id(), transition);
+}
+
fn consume_parser_inserted_script_prepare_state_with_async_attribute(
dom_host: &mut DomHost,
node: NativeNodeId,
diff --git a/moli-renderer-v8/src/host/scripts/runtime.rs b/moli-renderer-v8/src/host/scripts/runtime.rs
index fef956b0a..c56de688b 100644
--- a/moli-renderer-v8/src/host/scripts/runtime.rs
+++ b/moli-renderer-v8/src/host/scripts/runtime.rs
@@ -108,7 +108,7 @@ impl PreparedRuntimeScriptStart {
dom_host,
document,
node,
- ScriptElementLoaderOptions::default(),
+ ScriptElementLoaderOptions::with_scripting_enabled(true),
)
}
diff --git a/moli-renderer-v8/src/host/scripts/tests.rs b/moli-renderer-v8/src/host/scripts/tests.rs
index e7e40f1f7..c0184552a 100644
--- a/moli-renderer-v8/src/host/scripts/tests.rs
+++ b/moli-renderer-v8/src/host/scripts/tests.rs
@@ -1,9 +1,11 @@
use super::{
- HostScriptScheduler, ModuleFailurePolicy, PreparedRuntimeScriptStart, QueuedScriptFailureKind,
- RuntimeScriptPreparationContext, RuntimeScriptStartDecision, ScriptEventDispatchPolicy,
+ HostScriptScheduler, ModuleFailurePolicy, PreparedRuntimeScriptStart,
+ PreparedRuntimeScriptStartCommit, QueuedScriptFailureKind, RuntimeScriptPreparationContext,
+ RuntimeScriptStartDecision, ScriptElementLoaderOptions, ScriptEventDispatchPolicy,
ScriptEventPolicy, ScriptEventSkipReason, ScriptFailurePageTaskPolicy,
ScriptHandleExecutionSubject, ScriptHandleSource, ScriptHandleStartState,
- ScriptHostEventSubject, ScriptStartCommitKind, prepare_script_start,
+ ScriptHostEventSubject, ScriptStartCommitKind, plan_script_start,
+ prepare_runtime_script_start_commit, prepare_script_start,
};
use crate::{
dom::{
@@ -267,7 +269,7 @@ fn queueing_dynamic_module_does_not_block_later_import_map_merge() {
fn prepared_runtime_script_start_captures_document_and_base_urls_at_prepare_time() {
let initial_url =
Url::parse("https://example.test/base/").expect("initial test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
initial_url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -313,6 +315,79 @@ fn prepared_runtime_script_start_captures_document_and_base_urls_at_prepare_time
);
}
+#[test]
+fn scripting_disabled_runtime_scripts_commit_skip_without_queueing_work() {
+ for (label, src, source, script_type) in [
+ ("external classic", Some("blocked.js"), "", None),
+ ("inline classic", None, "globalThis.blocked = true", None),
+ (
+ "inline module",
+ None,
+ "globalThis.blockedModule = true",
+ Some("module"),
+ ),
+ (
+ "inline import map",
+ None,
+ r#"{"imports":{"blocked":"/blocked.js"}}"#,
+ Some("importmap"),
+ ),
+ ] {
+ let url = Url::parse("https://example.test/").expect("test url should parse");
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
+ url.clone(),
+ "<!doctype html><html><head></head><body></body></html>".to_owned(),
+ );
+ let mut dom_host = DomHost::from_dom(document.clone());
+ let body = document.document_body_handle().expect("body should exist");
+ let script = dom_host.create_element("script");
+ if let Some(src) = src {
+ assert!(dom_host.set_attribute(script, "src", src), "{label}");
+ }
+ if let Some(script_type) = script_type {
+ assert!(
+ dom_host.set_attribute(script, "type", script_type),
+ "{label}"
+ );
+ }
+ if !source.is_empty() {
+ assert!(dom_host.set_text_content(script, source), "{label}");
+ }
+ assert!(dom_host.append_child(body, script), "{label}");
+
+ let document_state = HostDocumentState::new(url);
+ let plan = plan_script_start(
+ &mut dom_host,
+ &document_state,
+ script,
+ &format!("disabled-{label}"),
+ ScriptElementLoaderOptions::with_scripting_enabled(false),
+ )
+ .unwrap_or_else(|| panic!("{label} should produce a start plan"));
+ let mut scripts = HostScriptScheduler::default();
+ let committed = prepare_runtime_script_start_commit(&mut dom_host, &mut scripts, plan)
+ .unwrap_or_else(|error| panic!("{label} skip commit failed: {error}"));
+
+ assert!(
+ matches!(committed, PreparedRuntimeScriptStartCommit::Noop),
+ "{label} must not produce executable work"
+ );
+ assert!(
+ dom_host
+ .node(script)
+ .and_then(Node::as_element)
+ .is_some_and(|element| element.script_already_started()),
+ "{label} must remain inert if scripting is enabled later"
+ );
+ let queued = scripts.drain_dynamic_scripts();
+ assert!(queued.in_order.is_empty(), "{label}");
+ assert!(queued.importmap_in_order.is_empty(), "{label}");
+ assert!(queued.module_in_order.is_empty(), "{label}");
+ assert!(queued.async_scripts.is_empty(), "{label}");
+ assert!(queued.failed_scripts.is_empty(), "{label}");
+ }
+}
+
#[test]
fn parser_inserted_classification_differs_from_dynamic_classification() {
let parser_mode = classify_script_mode(ScriptSchedulingInput {
@@ -356,7 +431,7 @@ fn parser_history_can_survive_without_falling_back_to_parser_owned_modes() {
#[test]
fn runtime_script_start_uses_language_attribute_when_type_is_absent() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body><script language='javascript'>window.ok = true;</script><script language=' javascript '>window.bad = true;</script></body></html>".to_owned(),
);
@@ -388,7 +463,7 @@ fn runtime_script_start_uses_language_attribute_when_type_is_absent() {
#[test]
fn runtime_script_start_applies_legacy_for_event_gate() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body><script for=' window ' event=' onload '>window.ok = true;</script><script for='window' event='onclick'>window.bad = true;</script></body></html>".to_owned(),
);
@@ -420,7 +495,7 @@ fn runtime_script_start_applies_legacy_for_event_gate() {
#[test]
fn runtime_svg_script_ignores_html_only_classification_attributes() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -462,7 +537,7 @@ fn runtime_svg_script_ignores_html_only_classification_attributes() {
#[test]
fn runtime_script_start_uses_direct_text_children_only() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -524,7 +599,7 @@ fn runtime_script_start_uses_direct_text_children_only() {
#[test]
fn runtime_owned_in_order_scripts_created_while_loading_do_not_wait_for_domcontentloaded() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -568,7 +643,7 @@ fn runtime_owned_in_order_scripts_created_while_loading_do_not_wait_for_domconte
#[test]
fn runtime_owned_module_scripts_created_while_loading_do_not_wait_for_domcontentloaded() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -616,7 +691,7 @@ fn runtime_owned_module_scripts_created_while_loading_do_not_wait_for_domcontent
#[test]
fn runtime_owned_in_order_scripts_created_after_loading_do_not_set_domcontentloaded_wait_flag() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -657,7 +732,7 @@ fn runtime_owned_in_order_scripts_created_after_loading_do_not_set_domcontentloa
#[test]
fn runtime_owned_handles_do_not_wait_for_blocking_stylesheets() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -682,7 +757,7 @@ fn runtime_owned_handles_do_not_wait_for_blocking_stylesheets() {
#[test]
fn parser_owned_handles_wait_for_blocking_stylesheets() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -707,7 +782,7 @@ fn parser_owned_handles_wait_for_blocking_stylesheets() {
#[test]
fn runtime_preparation_capture_uses_live_document_base_url() {
let url = Url::parse("https://example.test/page/index.html").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -755,7 +830,7 @@ fn runtime_preparation_capture_uses_live_document_base_url() {
#[test]
fn connected_datablock_type_mutation_alone_does_not_prepare() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -784,7 +859,7 @@ fn connected_datablock_type_mutation_alone_does_not_prepare() {
#[test]
fn parser_created_script_type_mutation_alone_does_not_prepare() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url,
"<!doctype html><html><head><script type=\"text/plain\">window.ran = true;</script></head></html>"
.to_owned(),
@@ -807,7 +882,7 @@ fn parser_created_script_type_mutation_alone_does_not_prepare() {
#[test]
fn parser_created_script_text_mutation_after_type_change_still_prepares() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url,
"<!doctype html><html><head><script type=\"text/plain\">window.ran = true;</script></head></html>"
.to_owned(),
@@ -832,7 +907,7 @@ fn parser_created_script_text_mutation_after_type_change_still_prepares() {
#[test]
fn parser_created_datablock_prepare_consumes_parser_inserted_state() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head><script type=\"text/plain\" src=\"/data.txt\"></script></head></html>"
.to_owned(),
@@ -900,7 +975,7 @@ fn parser_created_datablock_prepare_consumes_parser_inserted_state() {
#[test]
fn parser_created_external_script_reactivation_keeps_in_order_prepare_position() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head><script id=\"test\" type=\"text/plain\" src=\"/one.js\"></script></head></html>"
.to_owned(),
@@ -981,7 +1056,7 @@ fn parser_created_external_script_reactivation_keeps_in_order_prepare_position()
#[test]
fn parser_created_external_script_reactivation_without_async_false_stays_async() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head><script id=\"test\" type=\"text/plain\" src=\"/one.js\"></script></head></html>"
.to_owned(),
@@ -1056,7 +1131,7 @@ fn parser_created_external_script_reactivation_without_async_false_stays_async()
#[test]
fn prepare_script_start_invalid_external_src_queues_error_and_commits_start() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1127,7 +1202,7 @@ fn prepare_script_start_invalid_external_src_queues_error_and_commits_start() {
#[test]
fn prepare_script_start_empty_src_queues_async_error() {
let url = Url::parse("https://example.test/page.html").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1177,7 +1252,7 @@ fn prepare_script_start_empty_src_queues_async_error() {
#[test]
fn prepare_module_empty_src_queues_top_level_load_failure() {
let url = Url::parse("https://example.test/page.html").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1216,7 +1291,7 @@ fn prepare_module_empty_src_queues_top_level_load_failure() {
#[test]
fn prepare_script_start_invalid_importmap_src_queues_error_and_commits_start() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1292,7 +1367,7 @@ fn prepare_script_start_invalid_importmap_src_queues_error_and_commits_start() {
#[test]
fn prepare_script_start_registers_inline_importmap_without_script_queue() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1350,7 +1425,7 @@ fn prepare_script_start_registers_inline_importmap_without_script_queue() {
#[test]
fn invalid_inline_importmap_reports_failure_without_script_queue() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1391,7 +1466,7 @@ fn invalid_inline_importmap_reports_failure_without_script_queue() {
#[test]
fn prepare_script_start_nomodule_commits_skip_and_blocks_later_restart() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1467,7 +1542,7 @@ fn prepare_script_start_nomodule_commits_skip_and_blocks_later_restart() {
#[test]
fn prepare_script_start_external_importmap_commits_error_without_script_work() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1537,7 +1612,7 @@ fn prepare_script_start_external_importmap_commits_error_without_script_work() {
#[test]
fn prepare_script_start_committed_queue_stays_inert_across_src_mutation() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1598,7 +1673,7 @@ fn prepare_script_start_committed_queue_stays_inert_across_src_mutation() {
#[test]
fn prepare_script_start_reservation_blocks_orphaned_queue_entry_when_commit_is_denied() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -1656,7 +1731,7 @@ fn prepare_script_start_reservation_blocks_orphaned_queue_entry_when_commit_is_d
#[test]
fn prepare_script_start_committed_inline_execution_stays_inert_after_reattach() {
let url = Url::parse("https://example.test/").expect("test url should parse");
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
url.clone(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rs
index 06dadaa99..8174c773d 100644
--- a/moli-renderer-v8/src/lib.rs
+++ b/moli-renderer-v8/src/lib.rs
@@ -146,7 +146,7 @@ pub(crate) fn parse_html_test_fixture_with_parser_outputs(
Vec<parser::ParserScriptHandoff>,
Vec<DocumentOwnedBlockingStylesheetDiscoveryInput>,
) {
- let mut stream = parser::HtmlParser.start_document(final_url);
+ let mut stream = parser::HtmlParser::SCRIPTING_ENABLED.start_document(final_url);
stream.append_to_end(html);
let mut scripts = Vec::new();
let mut blocking_stylesheets = Vec::new();
diff --git a/moli-renderer-v8/src/live_document_parser.rs b/moli-renderer-v8/src/live_document_parser.rs
index 865c2708e..af12ae5cd 100644
--- a/moli-renderer-v8/src/live_document_parser.rs
+++ b/moli-renderer-v8/src/live_document_parser.rs
@@ -675,9 +675,9 @@ impl DocumentParserDriver {
}
impl DocumentParserSession {
- pub(crate) fn start_main_document(document_url: Url) -> Self {
+ pub(crate) fn start_main_document(document_url: Url, scripting_enabled: bool) -> Self {
Self::new_html(
- HtmlParser.start_document(document_url),
+ HtmlParser::with_scripting_enabled(scripting_enabled).start_document(document_url),
DocumentParserLifetime::Finite,
)
}
@@ -692,9 +692,11 @@ impl DocumentParserSession {
pub(crate) fn start_finite_live_document(
document_url: Url,
document_handle: NativeNodeId,
+ scripting_enabled: bool,
) -> Self {
Self::new_html(
- HtmlParser.start_live_document_root(document_url, document_handle),
+ HtmlParser::with_scripting_enabled(scripting_enabled)
+ .start_live_document_root(document_url, document_handle),
DocumentParserLifetime::Finite,
)
}
@@ -712,9 +714,11 @@ impl DocumentParserSession {
pub(crate) fn start_open_live_document(
document_url: Url,
document_handle: NativeNodeId,
+ scripting_enabled: bool,
) -> Self {
Self::new_html(
- HtmlParser.start_live_document_root(document_url, document_handle),
+ HtmlParser::with_scripting_enabled(scripting_enabled)
+ .start_live_document_root(document_url, document_handle),
DocumentParserLifetime::Open,
)
}
@@ -1193,6 +1197,7 @@ mod session_state_tests {
DocumentParserSession::start_finite_live_document(
Url::parse("https://parser-session.test/").expect("test URL"),
NativeNodeId::new(1),
+ true,
)
}
@@ -1234,6 +1239,7 @@ mod session_state_tests {
let mut parser = DocumentParserSession::start_open_live_document(
Url::parse("https://parser-session.test/").expect("test URL"),
NativeNodeId::new(1),
+ true,
);
let permit = parser.suspend(ParserSuspensionCause::ParserClassicSource {
script: NativeNodeId::new(8),
@@ -1365,6 +1371,7 @@ mod session_state_tests {
let mut parser = DocumentParserSession::start_open_live_document(
Url::parse("https://parser-session.test/").expect("test URL"),
NativeNodeId::new(1),
+ true,
);
let control = parser.control_handle();
let nesting = control.enter_parser_script_nesting();
diff --git a/moli-renderer-v8/src/mutation_coordinator.rs b/moli-renderer-v8/src/mutation_coordinator.rs
index 3ebed3f25..7e8e3dacd 100644
--- a/moli-renderer-v8/src/mutation_coordinator.rs
+++ b/moli-renderer-v8/src/mutation_coordinator.rs
@@ -441,7 +441,9 @@ impl MutationCoordinator {
dom_host,
document,
node,
- ScriptElementLoaderOptions::default(),
+ ScriptElementLoaderOptions::with_scripting_enabled(
+ unsafe { &*host_ptr }.document_scripting_enabled(owner_document_handle),
+ ),
)
.into_parts();
match decision {
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
index eebb70f7a..7a209a6a4 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
@@ -577,75 +577,14 @@ impl JsContextHost {
document_handle: DomHandle,
handoff: ParserScriptHandoff,
) -> ScriptDisposition {
- let (script_handle, start_line, start_column) = match &handoff {
- ParserScriptHandoff::BlockingClassic {
- node_id,
- start_line,
- start_column,
- ..
- }
- | ParserScriptHandoff::AsyncPostParse {
- node_id,
- start_line,
- start_column,
- ..
- }
- | ParserScriptHandoff::NonAsyncPostParse {
- node_id,
- start_line,
- start_column,
- ..
- }
- | ParserScriptHandoff::ImportMap {
- node_id,
- start_line,
- start_column,
- ..
- }
- | ParserScriptHandoff::NoExecution {
- node_id,
- start_line,
- start_column,
- ..
- }
- | ParserScriptHandoff::PreparationFailure {
- node_id,
- start_line,
- start_column,
- ..
- } => (*node_id, *start_line, *start_column),
- };
+ let (script_handle, start_line, start_column) = handoff.start_position();
self.note_parser_script_start_position(script_handle, start_line, start_column);
if !self.child_browsing_context_scripting_enabled(child_handle) {
- match handoff {
- ParserScriptHandoff::NoExecution {
- node_id, outcome, ..
- } => {
- crate::host::apply_parser_script_element_state_transition(
- self.dom_host_mut(),
- node_id,
- outcome.element_state_transition(),
- );
- }
- ParserScriptHandoff::PreparationFailure {
- node_id, failure, ..
- } => {
- crate::host::apply_parser_script_element_state_transition(
- self.dom_host_mut(),
- node_id,
- failure.element_state_transition(),
- );
- }
- ParserScriptHandoff::BlockingClassic { node_id, .. }
- | ParserScriptHandoff::AsyncPostParse { node_id, .. }
- | ParserScriptHandoff::NonAsyncPostParse { node_id, .. }
- | ParserScriptHandoff::ImportMap { node_id, .. } => {
- let _ = self
- .dom_host_mut()
- .set_script_already_started(node_id, true);
- }
- }
+ crate::host::apply_parser_script_element_state_without_execution(
+ self.dom_host_mut(),
+ &handoff,
+ );
return ScriptDisposition::Continue;
}
@@ -986,7 +925,7 @@ impl JsContextHost {
document_handle: DomHandle,
link_handles: Vec<DomHandle>,
) {
- if link_handles.is_empty() {
+ if link_handles.is_empty() || !self.child_browsing_context_scripting_enabled(child_handle) {
return;
}
for link_handle in link_handles {
@@ -1067,7 +1006,11 @@ impl JsContextHost {
.current_child_document_task_owner(child_handle)
.expect("committed child document-open parser must have a task owner");
assert_eq!(task_owner.document_owner(), owner);
- let parser = DocumentParserSession::start_open_live_document(document_url, document_handle);
+ let parser = DocumentParserSession::start_open_live_document(
+ document_url,
+ document_handle,
+ self.child_browsing_context_scripting_enabled(child_handle),
+ );
self.child_document_parsers.replace(owner, parser);
}
@@ -1577,7 +1520,11 @@ impl JsContextHost {
document_handle,
)
} else {
- DocumentParserSession::start_finite_live_document(document_base_url, document_handle)
+ DocumentParserSession::start_finite_live_document(
+ document_base_url,
+ document_handle,
+ self.child_browsing_context_scripting_enabled(child_handle),
+ )
};
let task_owner = self
.frame_owner_store
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rs
index 183f1501d..8e15266f7 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rs
@@ -122,6 +122,7 @@ mod tests {
DocumentParserSession::start_finite_live_document(
Url::parse("https://child-parser-store.test/").expect("test url"),
NativeNodeId::new(1),
+ true,
)
}
@@ -149,6 +150,7 @@ mod tests {
DocumentParserSession::start_open_live_document(
Url::parse("https://child-parser-store.test/").expect("test url"),
NativeNodeId::new(1),
+ true,
),
);
assert!(!store.is_complete_for(owner));
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots.rs
index d24e9f841..2a630e9e7 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots.rs
@@ -40,6 +40,10 @@ pub(crate) struct DetachedChildBrowsingContextDocumentSnapshot {
pub(crate) owner_node_id: crate::document_runtime::DomHandle,
pub(crate) url: Url,
pub(crate) markup: String,
+ /// Parser-only scripting state captured from the detached Document owner.
+ /// DOMSnapshot reparses `markup`, so it must preserve `<noscript>` semantics
+ /// without implying that snapshot parsing executes JavaScript.
+ pub(crate) scripting_enabled: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/detached.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/detached.rs
index fa024039d..f0fc5ffd5 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/detached.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/detached.rs
@@ -41,6 +41,7 @@ impl JsContextHost {
let Some(snapshot) = self.child_browsing_context_snapshot_markup(handle) else {
continue;
};
+ let scripting_enabled = self.child_browsing_context_scripting_enabled(handle);
let parent_scope = self
.child_browsing_context_web_storage_scope(
handle,
@@ -53,12 +54,14 @@ impl JsContextHost {
owner_node_id: handle,
url: snapshot.url.clone(),
markup: snapshot.markup.clone(),
+ scripting_enabled,
});
snapshots.extend(
self.detached_child_browsing_context_document_snapshots_in_markup(
&frame_id,
&snapshot.url,
&snapshot.markup,
+ scripting_enabled,
0,
parent_scope,
),
@@ -72,6 +75,7 @@ impl JsContextHost {
parent_frame_id: &str,
document_url: &Url,
markup: &str,
+ scripting_enabled: bool,
depth: usize,
parent_scope: WebStorageScope,
) -> Vec<DetachedChildBrowsingContextDocumentSnapshot> {
@@ -79,7 +83,8 @@ impl JsContextHost {
return Vec::new();
}
- let document = crate::parser::HtmlParser.parse(document_url.clone(), markup.to_owned());
+ let document = crate::parser::HtmlParser::with_scripting_enabled(scripting_enabled)
+ .parse(document_url.clone(), markup.to_owned());
let document_base_url = document
.document()
.map(|doc| doc.base_url().clone())
@@ -89,6 +94,7 @@ impl JsContextHost {
document.document_node_id(),
&document_base_url,
parent_frame_id,
+ scripting_enabled,
depth,
parent_scope,
)
@@ -100,6 +106,7 @@ impl JsContextHost {
root: DomHandle,
document_base_url: &Url,
parent_frame_id: &str,
+ document_scripting_enabled: bool,
depth: usize,
parent_scope: WebStorageScope,
) -> Vec<DetachedChildBrowsingContextDocumentSnapshot> {
@@ -133,18 +140,26 @@ impl JsContextHost {
security_origin_inherited,
parent_scope.clone(),
);
+ let scripting_enabled = Self::detached_child_document_scripting_enabled(
+ document,
+ child,
+ document_scripting_enabled,
+ &snapshot,
+ );
snapshots.push(DetachedChildBrowsingContextDocumentSnapshot {
parent_frame_id: parent_frame_id.to_owned(),
frame_id: frame_id.clone(),
owner_node_id: child,
url: snapshot.url.clone(),
markup: snapshot.markup.clone(),
+ scripting_enabled,
});
snapshots.extend(
self.detached_child_browsing_context_document_snapshots_in_markup(
&frame_id,
&snapshot.url,
&snapshot.markup,
+ scripting_enabled,
depth + 1,
parent_scope,
),
@@ -162,6 +177,7 @@ impl JsContextHost {
parent_frame_id: &str,
document_url: &Url,
markup: &str,
+ scripting_enabled: bool,
depth: usize,
parent_scope: WebStorageScope,
) -> Vec<ChildBrowsingContextFrameSnapshot> {
@@ -169,7 +185,8 @@ impl JsContextHost {
return Vec::new();
}
- let document = crate::parser::HtmlParser.parse(document_url.clone(), markup.to_owned());
+ let document = crate::parser::HtmlParser::with_scripting_enabled(scripting_enabled)
+ .parse(document_url.clone(), markup.to_owned());
let document_base_url = document
.document()
.map(|doc| doc.base_url().clone())
@@ -179,6 +196,7 @@ impl JsContextHost {
document.document_node_id(),
&document_base_url,
parent_frame_id,
+ scripting_enabled,
depth,
parent_scope,
)
@@ -190,6 +208,7 @@ impl JsContextHost {
root: DomHandle,
document_base_url: &Url,
parent_frame_id: &str,
+ document_scripting_enabled: bool,
depth: usize,
parent_scope: WebStorageScope,
) -> Vec<ChildBrowsingContextFrameSnapshot> {
@@ -204,6 +223,7 @@ impl JsContextHost {
document_base_url,
parent_frame_id,
snapshots.len() + 1,
+ document_scripting_enabled,
depth,
parent_scope.clone(),
));
@@ -222,6 +242,7 @@ impl JsContextHost {
document_base_url: &Url,
parent_frame_id: &str,
ordinal: usize,
+ document_scripting_enabled: bool,
depth: usize,
parent_scope: WebStorageScope,
) -> ChildBrowsingContextFrameSnapshot {
@@ -256,10 +277,17 @@ impl JsContextHost {
let child_frames = self
.detached_child_browsing_context_snapshot_markup(&bootstrap, document_base_url)
.map(|snapshot| {
+ let scripting_enabled = Self::detached_child_document_scripting_enabled(
+ document,
+ handle,
+ document_scripting_enabled,
+ &snapshot,
+ );
self.detached_child_browsing_context_frame_tree_snapshot(
&frame_id,
&snapshot.url,
&snapshot.markup,
+ scripting_enabled,
depth + 1,
storage_scope.clone(),
)
@@ -278,6 +306,20 @@ impl JsContextHost {
}
}
+ pub(in crate::native_bridge::context_host::child_frame_snapshots) fn detached_child_document_scripting_enabled(
+ document: &crate::dom::native::NativeDom,
+ owner: DomHandle,
+ parent_scripting_enabled: bool,
+ snapshot: &ChildBrowsingContextSnapshot,
+ ) -> bool {
+ parent_scripting_enabled
+ && super::super::child_frames::document_sandbox_policy_from_attribute(
+ document.get_attribute(owner, "sandbox").as_deref(),
+ )
+ .allows_scripts
+ && snapshot.policy_container.sandbox.allows_scripts
+ }
+
pub(in crate::native_bridge::context_host::child_frame_snapshots) fn is_detached_child_browsing_context_host_handle(
&self,
document: &crate::dom::native::NativeDom,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/document_lookup.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/document_lookup.rs
index a22011c5c..839690dd6 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/document_lookup.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/document_lookup.rs
@@ -31,11 +31,13 @@ impl JsContextHost {
let Some(snapshot) = self.child_browsing_context_snapshot_markup(handle) else {
continue;
};
+ let scripting_enabled = self.child_browsing_context_scripting_enabled(handle);
if let Some(snapshot) = self.find_detached_child_document_snapshot_by_frame_id(
&parent_frame_id,
frame_id,
&snapshot.url,
&snapshot.markup,
+ scripting_enabled,
0,
) {
return Some(snapshot);
@@ -79,13 +81,15 @@ impl JsContextHost {
target_frame_id: &str,
document_url: &Url,
markup: &str,
+ scripting_enabled: bool,
depth: usize,
) -> Option<ChildBrowsingContextDocumentSnapshot> {
if depth >= MAX_CHILD_FRAME_TREE_DEPTH {
return None;
}
- let document = crate::parser::HtmlParser.parse(document_url.clone(), markup.to_owned());
+ let document = crate::parser::HtmlParser::with_scripting_enabled(scripting_enabled)
+ .parse(document_url.clone(), markup.to_owned());
let document_base_url = document
.document()
.map(|doc| doc.base_url().clone())
@@ -96,6 +100,7 @@ impl JsContextHost {
&document_base_url,
parent_frame_id,
target_frame_id,
+ scripting_enabled,
depth,
)
}
@@ -107,6 +112,7 @@ impl JsContextHost {
document_base_url: &Url,
parent_frame_id: &str,
target_frame_id: &str,
+ document_scripting_enabled: bool,
depth: usize,
) -> Option<ChildBrowsingContextDocumentSnapshot> {
let mut ordinal = 0usize;
@@ -116,6 +122,7 @@ impl JsContextHost {
document_base_url,
parent_frame_id,
target_frame_id,
+ document_scripting_enabled,
depth,
&mut ordinal,
)
@@ -128,6 +135,7 @@ impl JsContextHost {
document_base_url: &Url,
parent_frame_id: &str,
target_frame_id: &str,
+ document_scripting_enabled: bool,
depth: usize,
ordinal: &mut usize,
) -> Option<ChildBrowsingContextDocumentSnapshot> {
@@ -144,6 +152,12 @@ impl JsContextHost {
&bootstrap,
document_base_url,
)?;
+ let scripting_enabled = Self::detached_child_document_scripting_enabled(
+ document,
+ child,
+ document_scripting_enabled,
+ &snapshot,
+ );
if frame_id == target_frame_id {
return Some(ChildBrowsingContextDocumentSnapshot {
url: snapshot.url.as_str().to_owned(),
@@ -155,6 +169,7 @@ impl JsContextHost {
target_frame_id,
&snapshot.url,
&snapshot.markup,
+ scripting_enabled,
depth + 1,
) {
return Some(found);
@@ -167,6 +182,7 @@ impl JsContextHost {
document_base_url,
parent_frame_id,
target_frame_id,
+ document_scripting_enabled,
depth,
ordinal,
) {
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rs
index 7df4f4450..de48201de 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/frame_tree.rs
@@ -34,6 +34,7 @@ impl JsContextHost {
"",
&snapshot.url,
&snapshot.markup,
+ self.child_browsing_context_scripting_enabled(handle),
0,
parent_scope,
)
@@ -74,6 +75,7 @@ impl JsContextHost {
"",
&snapshot.url,
&snapshot.markup,
+ self.child_browsing_context_scripting_enabled(handle),
0,
parent_scope,
)
@@ -135,6 +137,7 @@ impl JsContextHost {
&identity.frame_id,
&snapshot.url,
&snapshot.markup,
+ self.child_browsing_context_scripting_enabled(handle),
depth,
storage_scope.clone(),
)
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs
index e4e0be65d..e123e686c 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/request_scope.rs
@@ -162,6 +162,7 @@ impl JsContextHost {
pub(crate) fn child_browsing_context_base_url(&self, handle: DomHandle) -> Option<Url> {
let entry = self.child_browsing_contexts.get(&handle)?;
let document_url = self.child_browsing_context_current_url(handle)?;
+ let scripting_enabled = self.child_browsing_context_scripting_enabled(handle);
if entry.pending_attribute_bootstrap_commit()
&& let Some(snapshot) = self
.materialize_local_child_snapshot_for_bootstrap(handle, entry.attribute_bootstrap())
@@ -171,7 +172,11 @@ impl JsContextHost {
{
return Some(self.document_base_url_for_child_context(handle));
}
- return Some(child_snapshot_base_url(&snapshot, snapshot.url.clone()));
+ return Some(child_snapshot_base_url(
+ &snapshot,
+ snapshot.url.clone(),
+ scripting_enabled,
+ ));
}
let inherits_parent_about_blank = moli_url::is_about_blank(&document_url)
&& self.child_browsing_context_inherits_parent_origin(handle);
@@ -194,7 +199,11 @@ impl JsContextHost {
let Some(snapshot) = entry.cached_snapshot_ref() else {
return Some(document_url);
};
- Some(child_snapshot_base_url(snapshot, document_url))
+ Some(child_snapshot_base_url(
+ snapshot,
+ document_url,
+ scripting_enabled,
+ ))
}
pub(in crate::native_bridge::context_host) fn push_child_subresource_request_scope(
@@ -702,13 +711,44 @@ impl JsContextHost {
&& self
.child_browsing_contexts
.get(&handle)
- .is_none_or(|entry| entry.document_sandbox_allows_scripts())
+ .is_some_and(|entry| entry.document_sandbox_allows_scripts())
+ }
+
+ pub(crate) fn lightweight_popup_scripting_enabled(&self, popup_id: u64) -> bool {
+ !self.script_execution_disabled()
+ && self
+ .lightweight_popup_policy_container(popup_id)
+ .is_some_and(|policy| policy.sandbox.allows_scripts)
}
pub(crate) fn document_scripting_enabled(&self, document_handle: DomHandle) -> bool {
+ if document_handle == self.document_handle() {
+ return !self.script_execution_disabled()
+ && self.document_policy_container().sandbox.allows_scripts;
+ }
+ if let Some(popup_id) = self.lightweight_popup_id_for_document_handle(document_handle) {
+ return self.lightweight_popup_scripting_enabled(popup_id);
+ }
self.child_browsing_context_host_for_document_handle(document_handle)
.map(|handle| self.child_browsing_context_scripting_enabled(handle))
- .unwrap_or(true)
+ // DOMParser and document.implementation documents have no browsing
+ // context, so scripting is disabled for their fragment parsers too.
+ .unwrap_or(false)
+ }
+
+ pub(crate) fn owner_scripting_enabled(&self, owner: OwnerDispatchScope) -> bool {
+ match owner {
+ OwnerDispatchScope::Top => {
+ !self.script_execution_disabled()
+ && self.document_policy_container().sandbox.allows_scripts
+ }
+ OwnerDispatchScope::LightweightPopup(popup_id) => {
+ self.lightweight_popup_scripting_enabled(popup_id)
+ }
+ OwnerDispatchScope::Child(handle) => {
+ self.child_browsing_context_scripting_enabled(handle)
+ }
+ }
}
pub(crate) fn child_browsing_context_inherits_parent_origin(&self, handle: DomHandle) -> bool {
@@ -771,8 +811,13 @@ fn web_storage_key_for_origin_and_top_level_site_with_nonce(
MoliStorageKey::new(origin.to_owned(), top_level_site, opaque_nonce, relation)
}
-fn child_snapshot_base_url(snapshot: &ChildBrowsingContextSnapshot, fallback: Url) -> Url {
- let document = crate::parser::HtmlParser.parse(snapshot.url.clone(), snapshot.markup.clone());
+fn child_snapshot_base_url(
+ snapshot: &ChildBrowsingContextSnapshot,
+ fallback: Url,
+ scripting_enabled: bool,
+) -> Url {
+ let document = crate::parser::HtmlParser::with_scripting_enabled(scripting_enabled)
+ .parse(snapshot.url.clone(), snapshot.markup.clone());
document
.document()
.map(|doc| doc.base_url().clone())
diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs
index 975ed2afe..7411d9658 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs
@@ -858,12 +858,15 @@ impl JsContextHost {
self.lightweight_popup_window_names.insert(name, popup_id);
}
if moli_url::is_about_blank(&initial_url)
- && let Some(document) = crate::dom_parser::parse_detached_child_document_from_source(
+ && let Some(document) = crate::dom_parser::parse_child_document_projection_from_source(
scope,
initial_url.clone(),
"<!doctype html><html><head></head><body></body></html>",
Some("text/html"),
None,
+ crate::parser::HtmlParser::with_scripting_enabled(
+ self.lightweight_popup_scripting_enabled(popup_id),
+ ),
)
{
if let Some(document_handle) =
@@ -2077,12 +2080,15 @@ impl JsContextHost {
} else {
String::new()
};
- let Some(document) = crate::dom_parser::parse_detached_child_document_from_source(
+ let Some(document) = crate::dom_parser::parse_child_document_projection_from_source(
scope,
document_url,
"<!doctype html><html><head></head><body></body></html>",
Some("text/html"),
None,
+ crate::parser::HtmlParser::with_scripting_enabled(
+ self.lightweight_popup_scripting_enabled(popup_id),
+ ),
) else {
return;
};
@@ -2442,13 +2448,18 @@ impl JsContextHost {
&base_url,
&document_referrer,
);
- if let Some(document) = crate::dom_parser::parse_detached_child_document_from_source(
- scope,
- final_url.clone(),
- &loaded.markup,
- loaded.content_type.as_deref(),
- Some(&loaded.character_set),
- ) {
+ if let Some(document) =
+ crate::dom_parser::parse_child_document_projection_from_source(
+ scope,
+ final_url.clone(),
+ &loaded.markup,
+ loaded.content_type.as_deref(),
+ Some(&loaded.character_set),
+ crate::parser::HtmlParser::with_scripting_enabled(
+ self.lightweight_popup_scripting_enabled(popup_id),
+ ),
+ )
+ {
let host_ptr = self as *mut JsContextHost;
let document_base_url = lightweight_popup_parsed_document_base_url(
host_ptr, scope, document, &final_url,
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_install/accessors/iframe_content.rs b/moli-renderer-v8/src/native_bridge/document/detached_install/accessors/iframe_content.rs
index 05fd9fe82..72a825cf7 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_install/accessors/iframe_content.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_install/accessors/iframe_content.rs
@@ -45,12 +45,13 @@ pub(in crate::native_bridge) fn detached_iframe_content_document<'s>(
} else {
parsed_base_url
};
- let document = crate::dom_parser::parse_detached_child_document_from_source(
+ let document = crate::dom_parser::parse_child_document_projection_from_source(
scope,
snapshot.url.clone(),
&snapshot.markup,
snapshot.content_type.as_deref(),
Some(&snapshot.character_set),
+ HtmlParser::with_scripting_enabled(false),
)?;
if let Some(base_url) = v8_string(scope, base_url.as_str()) {
set_private_value(
@@ -154,7 +155,8 @@ fn detached_iframe_srcdoc_base_url<'s>(
}
fn snapshot_base_url(document_url: Url, markup: &str) -> Url {
- let document = HtmlParser.parse(document_url.clone(), markup.to_owned());
+ let document =
+ HtmlParser::with_scripting_enabled(false).parse(document_url.clone(), markup.to_owned());
document
.document()
.map(|doc| doc.base_url().clone())
diff --git a/moli-renderer-v8/src/native_bridge/element/event_handlers/shared.rs b/moli-renderer-v8/src/native_bridge/element/event_handlers/shared.rs
index 4e6ba0904..a9c1d73ac 100644
--- a/moli-renderer-v8/src/native_bridge/element/event_handlers/shared.rs
+++ b/moli-renderer-v8/src/native_bridge/element/event_handlers/shared.rs
@@ -76,6 +76,10 @@ fn compile_event_attribute_handler_for_owner_with_context<'s>(
arguments: &[v8::Local<'s, v8::String>],
context_extensions: &[v8::Local<'s, v8::Object>],
) -> Option<v8::Local<'s, v8::Function>> {
+ let host = unsafe { &*host_ptr };
+ if !host.owner_scripting_enabled(owner) {
+ return None;
+ }
if !unsafe { &mut *host_ptr }.allows_inline_event_handler_by_csp(scope, owner, source) {
return None;
}
diff --git a/moli-renderer-v8/src/runtime/page_dom_snapshot.rs b/moli-renderer-v8/src/runtime/page_dom_snapshot.rs
index 047932514..55a29acf7 100644
--- a/moli-renderer-v8/src/runtime/page_dom_snapshot.rs
+++ b/moli-renderer-v8/src/runtime/page_dom_snapshot.rs
@@ -348,8 +348,11 @@ fn detached_document_root(
owner_node_id,
url,
markup,
+ scripting_enabled,
} = snapshot;
- let dom_host = DomHost::from_dom(crate::parser::HtmlParser.parse(url, markup));
+ let dom_host = DomHost::from_dom(
+ crate::parser::HtmlParser::with_scripting_enabled(scripting_enabled).parse(url, markup),
+ );
let root =
live_document_node_snapshot(&dom_host, dom_host.dom().document_node_id(), -1, None, true)?;
Some(CapturedDocumentRoot {
@@ -609,6 +612,34 @@ fn text_content(snapshot: &DocumentNodeSnapshot) -> String {
mod tests {
use super::*;
use moli_page_types::DocumentNodeAssociatedSnapshot;
+ use url::Url;
+
+ fn snapshot_contains_element_id(snapshot: &DocumentNodeSnapshot, id: &str) -> bool {
+ snapshot
+ .attributes
+ .iter()
+ .any(|attribute| attribute.local_name == "id" && attribute.value == id)
+ || snapshot
+ .children
+ .iter()
+ .any(|child| snapshot_contains_element_id(child, id))
+ || snapshot
+ .shadow_roots
+ .iter()
+ .any(|root| snapshot_contains_element_id(root, id))
+ }
+
+ fn detached_noscript_document_root(scripting_enabled: bool) -> CapturedDocumentRoot {
+ detached_document_root(DetachedChildBrowsingContextDocumentSnapshot {
+ parent_frame_id: "parent".to_owned(),
+ frame_id: "child".to_owned(),
+ owner_node_id: crate::dom::native::NativeNodeId::new(7),
+ url: Url::parse("https://detached-dom-snapshot.test/").expect("test URL"),
+ markup: "<noscript><span id='fallback'></span></noscript>".to_owned(),
+ scripting_enabled,
+ })
+ .expect("detached document root")
+ }
fn element_snapshot(index: usize, child: Option<DocumentNodeSnapshot>) -> DocumentNodeSnapshot {
let children = child.into_iter().collect::<Vec<_>>();
@@ -673,6 +704,21 @@ mod tests {
);
}
+ #[test]
+ fn detached_dom_snapshot_reuses_document_scripting_policy() {
+ let enabled = detached_noscript_document_root(true);
+ assert!(
+ !snapshot_contains_element_id(&enabled.root, "fallback"),
+ "scripting-enabled noscript contents must remain text in DOMSnapshot fallback parsing"
+ );
+
+ let disabled = detached_noscript_document_root(false);
+ assert!(
+ snapshot_contains_element_id(&disabled.root, "fallback"),
+ "scripting-disabled noscript contents must remain markup in DOMSnapshot fallback parsing"
+ );
+ }
+
#[test]
fn node_table_excludes_template_content_association() {
let mut snapshot = element_snapshot(7, None);
diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rs
index 873b4255e..af363bb59 100644
--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs
@@ -4541,7 +4541,7 @@ impl PageVm {
request_url: &Url,
fetch_metadata: &crate::planning::ScriptFetchMetadata,
) -> ScannedScriptAdmission {
- if self.script_execution_disabled() {
+ if !self.main_document_scripting_enabled() {
return ScannedScriptAdmission::DeferredToParser(
ScannedScriptDeferral::ScriptExecutionDisabled,
);
@@ -5031,6 +5031,10 @@ impl PageVm {
self.vm().script_execution_disabled()
}
+ pub(super) fn main_document_scripting_enabled(&self) -> bool {
+ self.vm().document_runtime.document_scripting_enabled()
+ }
+
pub(crate) fn script_execution_control(
&self,
) -> crate::script_execution_control::RendererScriptExecutionControl {
diff --git a/moli-renderer-v8/src/runtime/page_vm/page_owned_document_script_hooks.rs b/moli-renderer-v8/src/runtime/page_vm/page_owned_document_script_hooks.rs
index d74996a23..1b22f9a4a 100644
--- a/moli-renderer-v8/src/runtime/page_vm/page_owned_document_script_hooks.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/page_owned_document_script_hooks.rs
@@ -78,7 +78,7 @@ impl PageOwnedDocumentScriptHooks for MainPageOwnedDocumentScriptHooks<'_, '_> {
) -> Pin<Box<dyn Future<Output = PageOwnedDocumentScriptBodyExecution> + 'a>> {
Box::pin(async move {
let local_executor = self.page_vm.local_executor.clone();
- let script_execution_disabled = self.page_vm.script_execution_disabled();
+ let script_execution_disabled = !self.page_vm.main_document_scripting_enabled();
let outcome = execute_prepared_script_on_script_execution_lane(
&local_executor,
self.loader,
diff --git a/moli-renderer-v8/src/runtime/page_vm/test_support.rs b/moli-renderer-v8/src/runtime/page_vm/test_support.rs
index b03d49a4c..e7c776bf7 100644
--- a/moli-renderer-v8/src/runtime/page_vm/test_support.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/test_support.rs
@@ -110,7 +110,7 @@ impl PageVmTaskExecutorTestHarness {
loader: &ResourceRequestClient,
browser_context_runtime: crate::runtime::RendererBrowserContextRuntime,
) -> Self {
- let dom_host = DomHost::from_dom(HtmlParser.parse(
+ let dom_host = DomHost::from_dom(HtmlParser::SCRIPTING_ENABLED.parse(
document_url,
"<!doctype html><html><head></head><body></body></html>".to_owned(),
));
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/lifecycle.rs b/moli-renderer-v8/src/runtime/page_vm/tests/lifecycle.rs
index 94741ed09..1cc7c320a 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/lifecycle.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/lifecycle.rs
@@ -3359,7 +3359,7 @@ fn page_state_capture_publishes_lightweight_document_metadata() {
crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
let document_url = Url::parse("https://metadata-cache.test/page").expect("document URL");
let dom_host = DomHost::from_dom(
- HtmlParser.parse(
+ HtmlParser::SCRIPTING_ENABLED.parse(
document_url.clone(),
"<!doctype html><html><head><title>metadata-title</title></head><body></body></html>"
.to_owned(),
@@ -3393,7 +3393,7 @@ fn serialize_html_reads_current_document_after_document_open() {
let loader =
crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
let document_url = Url::parse("https://document-cache.test/").expect("test URL");
- let dom_host = DomHost::from_dom(HtmlParser.parse(
+ let dom_host = DomHost::from_dom(HtmlParser::SCRIPTING_ENABLED.parse(
document_url,
"<!doctype html><html><head></head><body>before</body></html>".to_owned(),
));
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
index ebe039660..fda4a074f 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
@@ -1574,7 +1574,7 @@ fn test_page_vm_with_document_url(document_url: Url) -> PageVm {
fn test_page_vm_with_root_frame_id(root_frame_id: &str) -> PageVm {
let loader_owner =
crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
- let dom_host = DomHost::from_dom(HtmlParser.parse(
+ let dom_host = DomHost::from_dom(HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").expect("test Document URL"),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
));
@@ -1737,7 +1737,7 @@ fn test_page_vm_with_loader_document_url_hooks_and_response_referrer_policy(
runtime_hooks: PageVmRuntimeHooks,
response_referrer_policy: Option<String>,
) -> PageVm {
- let dom_host = DomHost::from_dom(HtmlParser.parse(
+ let dom_host = DomHost::from_dom(HtmlParser::SCRIPTING_ENABLED.parse(
document_url,
"<!doctype html><html><head></head><body></body></html>".to_owned(),
));
@@ -3152,7 +3152,7 @@ fn default_runtime_hooks_reject_direct_no_owner_page_vm_construction() {
reserved_service_worker_client_id: None,
},
PageVmRuntimeHooks::default(),
- DomHost::from_dom(HtmlParser.parse(
+ DomHost::from_dom(HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
)),
diff --git a/moli-renderer-v8/src/runtime/phase_one/bootstrap.rs b/moli-renderer-v8/src/runtime/phase_one/bootstrap.rs
index 8ee733368..e6db2f0ea 100644
--- a/moli-renderer-v8/src/runtime/phase_one/bootstrap.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/bootstrap.rs
@@ -65,19 +65,15 @@ impl ConcurrentParseTimeRuntime {
html: String,
started: Instant,
) -> Result<ParseTimePageVmCreationOutcome> {
- let mut state = ParseTimeDriverState::new(final_url.clone());
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled(
+ final_url.clone(),
+ main_document_parser_scripting_enabled(env),
+ );
state
.buffered_document_preloads
- .set_script_fetch_interception_enabled(
- env.fetch_subresource_interception_enabled
- && env.fetch_subresource_interception_resource_type.is_none_or(
- |resource_type| {
- resource_type.has_same_cdp_fetch_interception_type(
- crate::types::SubresourceResourceType::Script,
- )
- },
- ),
- );
+ .set_script_fetch_requires_owner_admission(script_preloads_require_owner_admission(
+ env,
+ ));
state
.buffered_document_preloads
.set_response_csp_requires_parser_admission(
@@ -150,16 +146,9 @@ impl ConcurrentParseTimeRuntime {
.set_xml_document_content_type(document_content_type);
state
.buffered_document_preloads
- .set_script_fetch_interception_enabled(
- env.fetch_subresource_interception_enabled
- && env.fetch_subresource_interception_resource_type.is_none_or(
- |resource_type| {
- resource_type.has_same_cdp_fetch_interception_type(
- crate::types::SubresourceResourceType::Script,
- )
- },
- ),
- );
+ .set_script_fetch_requires_owner_admission(script_preloads_require_owner_admission(
+ env,
+ ));
state
.buffered_document_preloads
.set_response_csp_requires_parser_admission(
diff --git a/moli-renderer-v8/src/runtime/phase_one/mod.rs b/moli-renderer-v8/src/runtime/phase_one/mod.rs
index 120f6a647..ee6592123 100644
--- a/moli-renderer-v8/src/runtime/phase_one/mod.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/mod.rs
@@ -95,6 +95,25 @@ mod non_executable_script_tests;
use super::script_preloads::*;
use super::script_preloads::{BufferedDocumentPreloadState, ServiceWorkerScriptPreloadContext};
+fn script_preloads_require_owner_admission(env: &PageVmEnvConfig) -> bool {
+ !main_document_parser_scripting_enabled(env)
+ || env.fetch_subresource_interception_enabled
+ && env
+ .fetch_subresource_interception_resource_type
+ .is_none_or(|resource_type| {
+ resource_type.has_same_cdp_fetch_interception_type(
+ crate::types::SubresourceResourceType::Script,
+ )
+ })
+}
+
+fn main_document_parser_scripting_enabled(env: &PageVmEnvConfig) -> bool {
+ !env.script_execution_disabled
+ && crate::content_security_policy::content_security_policy_sandbox_allows_scripts(
+ &env.response_content_security_policies,
+ )
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -213,7 +232,10 @@ mod tests {
let loader = Box::leak(Box::new(
ResourceRequestClient::new(&FetchConfig::default()).expect("default loader"),
));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled(
+ final_url,
+ main_document_parser_scripting_enabled(&env),
+ )));
let parser_dom_host = state
.parser_session
.stream_handle()
@@ -414,7 +436,7 @@ mod tests {
.await
}
- async fn parse_phase_one_html_into_page_vm_for_test_with_env(
+ pub(super) async fn parse_phase_one_html_into_page_vm_for_test_with_env(
html: &'static str,
env: PageVmEnvConfig,
) -> PageVm {
@@ -452,6 +474,65 @@ mod tests {
page_vm
}
+ #[test]
+ fn main_document_parser_derives_scripting_state_from_runtime_and_response_sandbox() {
+ const MARKUP: &str = "<!doctype html><noscript><main id='fallback'></main></noscript>";
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("current-thread runtime should build");
+
+ runtime.block_on(tokio::task::LocalSet::new().run_until(async {
+ for (script_execution_disabled, policy, fallback_expected) in [
+ (false, None, false),
+ (true, None, true),
+ (false, Some("script-src 'none'"), false),
+ (false, Some("sandbox"), true),
+ (false, Some("sandbox allow-scripts"), false),
+ ] {
+ let env = default_test_page_vm_env_config_with(|env| {
+ env.script_execution_disabled = script_execution_disabled;
+ env.response_content_security_policies =
+ policy.into_iter().map(str::to_owned).collect();
+ });
+ let page_vm =
+ parse_phase_one_html_into_page_vm_for_test_with_env(MARKUP, env).await;
+ let fallback_present = page_vm
+ .vm()
+ .document_runtime
+ .dom_host()
+ .element_handle_by_id("fallback")
+ .is_some();
+ assert_eq!(
+ fallback_present, fallback_expected,
+ "unexpected noscript parse for disabled={script_execution_disabled}, policy={policy:?}"
+ );
+ }
+
+ for (policy, script_expected) in
+ [("sandbox", false), ("sandbox allow-scripts", true)]
+ {
+ let env = default_test_page_vm_env_config_with(|env| {
+ env.response_content_security_policies = vec![policy.to_owned()];
+ });
+ let page_vm = parse_phase_one_html_into_page_vm_for_test_with_env(
+ "<!doctype html><script>document.documentElement.setAttribute('data-script-ran', 'yes')</script>",
+ env,
+ )
+ .await;
+ let dom_host = page_vm.vm().document_runtime.dom_host();
+ let document_element = dom_host
+ .document_element_handle()
+ .expect("parser should create the document element");
+ assert_eq!(
+ dom_host.get_attribute(document_element, "data-script-ran").is_some(),
+ script_expected,
+ "unexpected parser script execution for policy={policy:?}"
+ );
+ }
+ }));
+ }
+
#[test]
fn layout_renderer_constructs_phase_one_roles_from_native_dom_and_stylo() {
let runtime = tokio::runtime::Builder::new_current_thread()
@@ -1996,7 +2077,7 @@ document.body.setAttribute('data-error-state', [
}
}
- fn default_test_page_vm_env_config_with(
+ pub(super) fn default_test_page_vm_env_config_with(
update: impl FnOnce(&mut PageVmEnvConfig),
) -> PageVmEnvConfig {
let mut env = default_test_page_vm_env_config();
@@ -2746,6 +2827,41 @@ document.body.setAttribute('data-error-state', [
assert_eq!(cache.pending_preload_counts_for_test(), (1, 0));
}
+ #[test]
+ fn script_disabled_preload_scan_defers_every_script_to_the_page_owner() {
+ let final_url = Url::parse("https://example.test/docs/page.html").expect("test url");
+ let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
+ let env = default_test_page_vm_env_config_with(|env| {
+ env.script_execution_disabled = true;
+ });
+ let mut cache = BufferedDocumentPreloadState::default();
+ cache.set_script_fetch_requires_owner_admission(script_preloads_require_owner_admission(
+ &env,
+ ));
+
+ cache.append_to_main_document_scan(
+ &final_url,
+ concat!(
+ "<script src='/blocking.js'></script>",
+ "<script defer src='/defer.js'></script>",
+ "<script async src='/async.js'></script>",
+ "<script type='module' src='/module.js'></script>",
+ ),
+ &loader,
+ );
+
+ assert!(
+ cache.entries.is_empty(),
+ "the preload scanner must not start a physical script fetch before the disabled page owner can reject it"
+ );
+ assert_eq!(
+ preload_request_urls(cache.take_pending_script_preloads_for_test()),
+ ["blocking.js", "defer.js", "async.js", "module.js"].map(|name| {
+ Url::parse(&format!("https://example.test/{name}")).expect("script preload URL")
+ })
+ );
+ }
+
#[test]
fn meta_csp_gate_waits_for_every_scanner_seen_policy() {
let final_url = Url::parse("https://example.test/docs/page.html").expect("test url");
@@ -2961,7 +3077,7 @@ document.body.setAttribute('data-error-state', [
"#;
let loader = ResourceRequestClient::new(&FetchConfig::default())
.expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url.clone());
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url.clone());
let parser_dom_host = state
.parser_session
.stream_handle()
@@ -3786,7 +3902,7 @@ document.body.setAttribute('data-error-state', [
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -3890,7 +4006,7 @@ document.body.setAttribute('data-error-state', [
let loader_owner =
ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
let loader = loader_owner.clone();
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
state.close_input();
let parser_bridge =
crate::document_runtime::ParserConnectedScriptBridge::for_session(
@@ -4016,7 +4132,7 @@ document.body.setAttribute('data-error-state', [
let loader = Box::leak(Box::new(
ResourceRequestClient::new(&FetchConfig::default()).expect("default loader"),
));
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let parser_dom_host = state
.parser_session
.stream_handle()
@@ -4107,7 +4223,7 @@ document.body.setAttribute('data-error-state', [
let loader = Box::leak(Box::new(
ResourceRequestClient::new(&FetchConfig::default()).expect("default loader"),
));
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let parser_dom_host = state
.parser_session
.stream_handle()
@@ -4676,7 +4792,7 @@ queueMicrotask(() => window.__mainParserClassicCheckpointEvents.push('script-mic
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
state.input_closed = true;
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
@@ -4796,7 +4912,7 @@ queueMicrotask(() => window.__mainParserClassicCheckpointEvents.push('script-mic
let final_url = Url::parse("https://example.test/").expect("test url");
let loader: &'static ResourceRequestClient =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -4862,7 +4978,7 @@ queueMicrotask(() => window.__mainParserClassicCheckpointEvents.push('script-mic
let _js_runtime = crate::JsRuntime::initialize();
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -5073,7 +5189,7 @@ queueMicrotask(() => window.__mainParserClassicCheckpointEvents.push('script-mic
let final_url = Url::parse("https://example.test/").expect("test url");
let loader: &'static ResourceRequestClient =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let env = default_test_page_vm_env_config_with(|env| {
@@ -5149,7 +5265,7 @@ queueMicrotask(() => window.__mainParserClassicCheckpointEvents.push('script-mic
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let env = default_test_page_vm_env_config_with(|env| {
@@ -5372,7 +5488,7 @@ globalThis.__outerDocumentWriteScriptContinued = true;
runtime.block_on(async move {
let final_url = Url::parse("https://example.test/docs/page.html").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
bind_preload_state_to_current_test_runtime(&mut state.buffered_document_preloads);
let session = state.parser_session.stream_handle().borrow().script_input_session();
session.enqueue_script_input_preload_html("<script sr".to_owned());
@@ -5470,7 +5586,8 @@ globalThis.__outerDocumentWriteScriptContinued = true;
let (script_url, server) = spawn_single_script_server(script_body).await;
let final_url = Url::parse("https://example.test/docs/page.html").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url.clone());
+ let mut state =
+ ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url.clone());
let browser_context_owner = crate::runtime::RendererBrowserContextRuntime::new();
let browser_context_runtime = browser_context_owner.handle();
let completion_queue = crate::page_task_queue::RendererPageServiceWorkerTestHarness::new();
@@ -5563,7 +5680,7 @@ globalThis.__outerDocumentWriteScriptContinued = true;
runtime.block_on(async move {
let final_url = Url::parse("https://example.test/docs/page.html").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
bind_preload_state_to_current_test_runtime(&mut state.buffered_document_preloads);
let session = state.parser_session.stream_handle().borrow().script_input_session();
@@ -5609,7 +5726,7 @@ globalThis.__outerDocumentWriteScriptContinued = true;
#[test]
fn parse_time_driver_state_can_select_live_stream_backend_for_testing() {
let final_url = Url::parse("https://example.test/").expect("test url");
- let state = ParseTimeDriverState::new(final_url);
+ let state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
assert!(
state
@@ -5624,7 +5741,7 @@ globalThis.__outerDocumentWriteScriptContinued = true;
fn parser_owner_boundary_with_live_backend_queues_document_turn_before_runtime_work() {
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let mut owner = ParseTimeOwner::Parser;
let mut parser_step_ready = false;
let mut pending_parsing_blocking_wait = PendingParsingBlockingWait::None;
@@ -5761,7 +5878,7 @@ globalThis.__outerDocumentWriteScriptContinued = true;
let _js_runtime = crate::JsRuntime::initialize();
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -5845,7 +5962,7 @@ globalThis.__outerDocumentWriteScriptContinued = true;
fn parser_step_without_script_handoff_consumes_live_backend_dom() {
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -5901,7 +6018,7 @@ globalThis.__outerDocumentWriteScriptContinued = true;
fn parser_step_with_inline_script_surfaces_handoff_on_live_backend() {
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -5965,7 +6082,7 @@ globalThis.__outerDocumentWriteScriptContinued = true;
fn parser_step_with_inline_svg_script_surfaces_shared_script_handoff() {
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -13523,7 +13640,7 @@ document.body.append(window.jsRemovedLazyMedia, window.parserRemovedLazyMedia);
let final_url = Url::parse("https://example.test/").expect("test url");
let loader: &'static ResourceRequestClient =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url.clone())));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url.clone())));
let _js_runtime = crate::JsRuntime::initialize();
let mut driver = ParserDriver {
loader,
@@ -13604,7 +13721,7 @@ document.body.setAttribute('data-result', `${before}|${style.color}`);
let final_url = Url::parse("https://example.test/").expect("test url");
let loader: &'static ResourceRequestClient =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url.clone())));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url.clone())));
let _js_runtime = crate::JsRuntime::initialize();
let mut driver = ParserDriver {
loader,
@@ -13703,7 +13820,7 @@ document.body.setAttribute('data-result', `${before}|${style.color}`);
Url::parse("https://parser-sync-custom-element.test/").expect("test url");
let loader: &'static ResourceRequestClient =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url.clone())));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url.clone())));
let mut driver = ParserDriver {
loader,
final_url: &state.final_url,
@@ -13822,7 +13939,7 @@ document.body.setAttribute('data-result', [
Url::parse("https://parser-returned-custom-element.test/").expect("test url");
let loader: &'static ResourceRequestClient =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url.clone())));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url.clone())));
let mut driver = ParserDriver {
loader,
final_url: &state.final_url,
@@ -13962,7 +14079,7 @@ document.body.setAttribute('data-result', [
runtime.block_on(tokio::task::LocalSet::new().run_until(async move {
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let state = ParseTimeDriverState::new(final_url.clone());
+ let state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url.clone());
let _js_runtime = crate::JsRuntime::initialize();
let html =
r#"<!doctype html><style>div { color: red } .foo { color: lime }</style><body><div id="target"></div></body>"#;
@@ -14036,7 +14153,7 @@ document.body.setAttribute('data-result', [
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url.clone())));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url.clone())));
let mut driver = ParserDriver {
loader,
final_url: &state.final_url,
@@ -14210,7 +14327,7 @@ document.body.setAttribute('data-result', [
let loader = Box::leak(Box::new(
ResourceRequestClient::new(&FetchConfig::default()).expect("default loader"),
));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url.clone())));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url.clone())));
let mut driver = ParserDriver {
loader,
final_url: &state.final_url,
@@ -14459,7 +14576,7 @@ document.body.setAttribute('data-result', [
let loader = Box::leak(Box::new(
ResourceRequestClient::new(&FetchConfig::default()).expect("default loader"),
));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url.clone())));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url.clone())));
let mut driver = ParserDriver {
loader,
final_url: &state.final_url,
@@ -14665,7 +14782,7 @@ document.body.setAttribute('data-result', [
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -14831,7 +14948,7 @@ for (const [id, flag] of [
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -14907,7 +15024,7 @@ document.body.setAttribute('data-result', 'done');
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -14991,7 +15108,7 @@ document.body.setAttribute('data-result', [
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -15165,7 +15282,7 @@ document.body.setAttribute('data-parser-returned', [
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -15334,7 +15451,7 @@ document.body.setAttribute('data-idl-nonce', element.nonce);
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -15572,7 +15689,7 @@ document.body.setAttribute('data-input', [
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -15750,7 +15867,7 @@ document.body.setAttribute('data-face-disabled', String(face.matches(':disabled'
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -15864,7 +15981,7 @@ document.body.setAttribute('data-after-visible', String(!!document.getElementByI
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -15986,7 +16103,7 @@ document.body.setAttribute('data-after-body-visible', String(!!document.getEleme
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -16076,7 +16193,7 @@ document.body.setAttribute('data-token', instance.getAttribute('data-token') ||
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -16219,7 +16336,7 @@ document.body.setAttribute('data-bad-write', String(!!document.getElementById('b
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -16292,7 +16409,8 @@ document.body.setAttribute("data-range", [
fn inline_script_handoff_is_classified_as_blocking_classic_on_live_backend() {
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url.clone());
+ let mut state =
+ ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url.clone());
let driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -16349,7 +16467,7 @@ document.body.setAttribute("data-range", [
let _js_runtime = crate::JsRuntime::initialize();
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let mut driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -16450,7 +16568,7 @@ document.body.setAttribute("data-range", [
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
let mut state =
- ParseTimeDriverState::new(final_url);
+ ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let mut driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -16590,7 +16708,7 @@ document.body.setAttribute("data-range", [
let _js_runtime = crate::JsRuntime::initialize();
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let mut driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -16719,7 +16837,7 @@ document.body.setAttribute("data-range", [
let _js_runtime = crate::JsRuntime::initialize();
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let mut driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -16914,7 +17032,7 @@ document.body.setAttribute("data-range", [
let _js_runtime = crate::JsRuntime::initialize();
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let mut driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -17044,7 +17162,7 @@ document.body.setAttribute("data-range", [
let _js_runtime = crate::JsRuntime::initialize();
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let mut driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -17140,7 +17258,7 @@ document.body.setAttribute("data-range", [
let _js_runtime = crate::JsRuntime::initialize();
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let mut driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -17248,7 +17366,7 @@ document.body.setAttribute("data-range", [
let final_url = Url::parse("https://example.test/").expect("test url");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("default loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let mut driver = ParserDriver {
loader,
final_url: &state.final_url,
@@ -17384,7 +17502,7 @@ document.body.setAttribute("data-range", [
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
let mut state =
- ParseTimeDriverState::new(final_url);
+ ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let driver = ParserDriver {
loader: &loader,
final_url: &state.final_url,
@@ -17452,7 +17570,7 @@ document.body.setAttribute("data-range", [
let _js_runtime = crate::JsRuntime::initialize();
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let parser_dom_host = state.parser_session.stream_handle().borrow_mut().take_parser_stream_dom_host();
let local_executor = JsLocalExecutor::new();
let mut page_vm = PageVm::new(
@@ -17542,7 +17660,7 @@ document.body.setAttribute("data-range", [
let _js_runtime = crate::JsRuntime::initialize();
let final_url = Url::parse("https://example.test/").expect("test url");
let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let parser_dom_host = state
.parser_session
.stream_handle()
diff --git a/moli-renderer-v8/src/runtime/phase_one/non_executable_script_tests.rs b/moli-renderer-v8/src/runtime/phase_one/non_executable_script_tests.rs
index 7e363aeb6..5918b51c0 100644
--- a/moli-renderer-v8/src/runtime/phase_one/non_executable_script_tests.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/non_executable_script_tests.rs
@@ -14,7 +14,7 @@ fn data_block_completes_in_parser_turn_without_page_task() {
let final_url = Url::parse("https://example.test/").expect("test URL");
let loader =
Box::leak(Box::new(ResourceRequestClient::new(&FetchConfig::default()).expect("test loader")));
- let state = Box::leak(Box::new(ParseTimeDriverState::new(final_url)));
+ let state = Box::leak(Box::new(ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url)));
let parser_dom_host = state
.parser_session
.stream_handle()
@@ -109,3 +109,49 @@ document.body.setAttribute(
}));
});
}
+
+#[test]
+fn parser_owned_import_map_is_not_registered_when_script_execution_is_disabled() {
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("current-thread runtime should build");
+
+ runtime.block_on(tokio::task::LocalSet::new().run_until(async move {
+ let env = super::tests::default_test_page_vm_env_config_with(|env| {
+ env.script_execution_disabled = true;
+ });
+ let mut page_vm = super::tests::parse_phase_one_html_into_page_vm_for_test_with_env(
+ r#"<!doctype html><html><head><script type="importmap">{"imports":{"fixture":"/module.mjs"}}</script></head><body></body></html>"#,
+ env,
+ )
+ .await;
+ let base_url = Url::parse("https://example.test/").expect("base url");
+
+ assert!(
+ page_vm
+ .vm_mut()
+ .document_runtime
+ .resolve_module_specifier("fixture", &base_url)
+ .is_err(),
+ "a disabled parser-owned import map must not alter module resolution"
+ );
+ let document = page_vm.vm().document_runtime.dom_host().document_handle();
+ let scripts = page_vm
+ .vm()
+ .document_runtime
+ .dom_host()
+ .script_handles_in_subtree(document);
+ assert_eq!(scripts.len(), 1);
+ assert!(
+ page_vm
+ .vm()
+ .document_runtime
+ .dom_host()
+ .node(scripts[0])
+ .and_then(Node::as_element)
+ .is_some_and(|element| element.script_already_started()),
+ "the disabled import map must remain inert if scripting is enabled later"
+ );
+ }));
+}
diff --git a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_source.rs b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_source.rs
index 2a319cbc9..ee6bcc611 100644
--- a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_source.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_source.rs
@@ -128,7 +128,7 @@ pub(super) fn parser_blocking_script_can_start_external_source_load(
page_vm: &PageVm,
script: &PreparedScript,
) -> bool {
- if page_vm.script_execution_disabled() {
+ if !page_vm.main_document_scripting_enabled() {
return false;
}
if script.source_kind != crate::types::ScriptSourceKind::External {
diff --git a/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs b/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs
index 8babe5985..03790eaaa 100644
--- a/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs
@@ -31,6 +31,17 @@ use crate::parser_script::payload::{ParserClassicScriptMetadata, ParserPreparedC
use crate::planning::PreparedScript;
use html5ever::tree_builder::QuirksMode;
+fn disabled_script_run(script: &PreparedScript) -> crate::types::ScriptRun {
+ crate::types::ScriptRun::skipped(
+ script.node_id,
+ script.kind,
+ script.mode,
+ script.source_kind,
+ script.url.clone(),
+ crate::types::ScriptSkipReason::ScriptExecutionDisabled,
+ )
+}
+
struct PhaseOneParserOwner<'a> {
vm: &'a mut ScriptVm,
}
@@ -810,6 +821,66 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
.await
}
+ fn suppress_parser_script_handoff_if_scripting_is_disabled(
+ &mut self,
+ page_vm: &mut PageVm,
+ handoff: &ParserScriptHandoff,
+ ) -> bool {
+ if page_vm.main_document_scripting_enabled()
+ || matches!(handoff, ParserScriptHandoff::NoExecution { .. })
+ {
+ return false;
+ }
+
+ let (run, parser_blocking) = match handoff {
+ ParserScriptHandoff::BlockingClassic { script, .. } => {
+ (Some(disabled_script_run(script)), true)
+ }
+ ParserScriptHandoff::AsyncPostParse { script, .. }
+ | ParserScriptHandoff::NonAsyncPostParse { script, .. } => {
+ (Some(disabled_script_run(script)), false)
+ }
+ ParserScriptHandoff::ImportMap { import_map, .. } => {
+ let source_kind = match &import_map.source {
+ crate::parser::PreparedImportMapSource::Inline(_) => {
+ crate::types::ScriptSourceKind::Inline
+ }
+ crate::parser::PreparedImportMapSource::ExternalUnsupported => {
+ crate::types::ScriptSourceKind::External
+ }
+ };
+ (
+ Some(crate::types::ScriptRun::skipped(
+ import_map.node_id,
+ crate::types::ScriptKind::ImportMap,
+ crate::types::ScriptMode::ImportMapInOrder,
+ source_kind,
+ import_map.base_url.clone(),
+ crate::types::ScriptSkipReason::ScriptExecutionDisabled,
+ )),
+ false,
+ )
+ }
+ ParserScriptHandoff::PreparationFailure { .. } => (None, false),
+ ParserScriptHandoff::NoExecution { .. } => unreachable!(),
+ };
+ let (handle, start_line, start_column) = handoff.start_position();
+
+ page_vm
+ .vm_mut()
+ .document_runtime
+ .note_parser_script_start_position(handle, start_line, start_column);
+ crate::host::apply_parser_script_element_state_without_execution(
+ page_vm.vm_mut().document_runtime.dom_host_mut(),
+ handoff,
+ );
+ page_vm.report.runs.extend(run);
+ if parser_blocking {
+ self.finish_parser_blocking_pause();
+ }
+ true
+ }
+
async fn handle_parse_time_script_handoff_for_owner(
&mut self,
page_vm: &mut PageVm,
@@ -826,6 +897,9 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
);
return Ok(ScriptHandoffOutcome::StoppedCurrentDocument);
}
+ if self.suppress_parser_script_handoff_if_scripting_is_disabled(page_vm, &handoff) {
+ return Ok(ScriptHandoffOutcome::NoNavigation);
+ }
match handoff {
ParserScriptHandoff::BlockingClassic {
node_id: handle,
@@ -1399,43 +1473,45 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
page_vm
.vm_mut()
.accept_parser_discovered_native_modulepreloads(modulepreload_link_candidates);
- for mut script in async_prefetch_scripts {
- bind_parser_owned_script_handle(page_vm, &mut script);
- self.buffered_document_preloads
- .claim_pending_script_preload_for_parser(&script);
- let shared_preload = self
- .buffered_document_preloads
- .shared_preload_for_script(&script);
- let document_character_set = page_vm
- .vm()
- .document_runtime
- .document_character_set()
- .to_owned();
- let resource_task_runner = page_vm.resource_task_runner();
- let _ = self.scheduler.accept_parser_discovered_async_candidate(
- script,
- self.loader,
- resource_task_runner,
- shared_preload,
- Some(&document_character_set),
- |script| {
- let binding = page_vm
- .vm_mut()
- .accept_main_document_script_load_delay_binding(
- parser_document_owner,
- crate::frame_owner_model::MainDocumentScriptLoadDelayKind::Classic,
- )
- .expect("current parser async discovery must bind lifecycle ownership");
- tracing::debug!(
- ?parser_document_owner,
- script_node_id = ?script.node_id,
- script_url = %script.url,
- load_delay_token = ?binding.load_delay_token(),
- "accepted main parser async classic lifecycle binding before source work"
- );
- binding
- },
- );
+ if page_vm.main_document_scripting_enabled() {
+ for mut script in async_prefetch_scripts {
+ bind_parser_owned_script_handle(page_vm, &mut script);
+ self.buffered_document_preloads
+ .claim_pending_script_preload_for_parser(&script);
+ let shared_preload = self
+ .buffered_document_preloads
+ .shared_preload_for_script(&script);
+ let document_character_set = page_vm
+ .vm()
+ .document_runtime
+ .document_character_set()
+ .to_owned();
+ let resource_task_runner = page_vm.resource_task_runner();
+ let _ = self.scheduler.accept_parser_discovered_async_candidate(
+ script,
+ self.loader,
+ resource_task_runner,
+ shared_preload,
+ Some(&document_character_set),
+ |script| {
+ let binding = page_vm
+ .vm_mut()
+ .accept_main_document_script_load_delay_binding(
+ parser_document_owner,
+ crate::frame_owner_model::MainDocumentScriptLoadDelayKind::Classic,
+ )
+ .expect("current parser async discovery must bind lifecycle ownership");
+ tracing::debug!(
+ ?parser_document_owner,
+ script_node_id = ?script.node_id,
+ script_url = %script.url,
+ load_delay_token = ?binding.load_delay_token(),
+ "accepted main parser async classic lifecycle binding before source work"
+ );
+ binding
+ },
+ );
+ }
}
page_vm
.vm_mut()
diff --git a/moli-renderer-v8/src/runtime/phase_one/state.rs b/moli-renderer-v8/src/runtime/phase_one/state.rs
index 54d48526d..1b84dcb16 100644
--- a/moli-renderer-v8/src/runtime/phase_one/state.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/state.rs
@@ -14,9 +14,17 @@ pub(super) struct ParseTimeDriverState {
}
impl ParseTimeDriverState {
- pub(super) fn new(final_url: Url) -> Self {
+ #[cfg(test)]
+ pub(super) fn new_with_scripting_enabled_for_test(final_url: Url) -> Self {
+ Self::new_with_scripting_enabled(final_url, true)
+ }
+
+ pub(super) fn new_with_scripting_enabled(final_url: Url, scripting_enabled: bool) -> Self {
Self {
- parser_session: DocumentParserSession::start_main_document(final_url.clone()),
+ parser_session: DocumentParserSession::start_main_document(
+ final_url.clone(),
+ scripting_enabled,
+ ),
final_url,
document_character_set: "UTF-8".to_owned(),
scheduler: DocumentScriptScheduler::new(),
diff --git a/moli-renderer-v8/src/runtime/phase_one/streaming.rs b/moli-renderer-v8/src/runtime/phase_one/streaming.rs
index 045693ed4..defab9ab9 100644
--- a/moli-renderer-v8/src/runtime/phase_one/streaming.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/streaming.rs
@@ -139,19 +139,15 @@ impl ConcurrentParseTimeRuntime {
&response_final_url,
&response_headers,
);
- let mut state = ParseTimeDriverState::new(response_final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled(
+ response_final_url,
+ main_document_parser_scripting_enabled(&env),
+ );
state
.buffered_document_preloads
- .set_script_fetch_interception_enabled(
- env.fetch_subresource_interception_enabled
- && env.fetch_subresource_interception_resource_type.is_none_or(
- |resource_type| {
- resource_type.has_same_cdp_fetch_interception_type(
- crate::types::SubresourceResourceType::Script,
- )
- },
- ),
- );
+ .set_script_fetch_requires_owner_admission(script_preloads_require_owner_admission(
+ &env,
+ ));
state
.buffered_document_preloads
.set_response_csp_requires_parser_admission(
@@ -416,19 +412,15 @@ impl ConcurrentParseTimeRuntime {
},
)));
}
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled(
+ final_url,
+ main_document_parser_scripting_enabled(&env),
+ );
state
.buffered_document_preloads
- .set_script_fetch_interception_enabled(
- env.fetch_subresource_interception_enabled
- && env.fetch_subresource_interception_resource_type.is_none_or(
- |resource_type| {
- resource_type.has_same_cdp_fetch_interception_type(
- crate::types::SubresourceResourceType::Script,
- )
- },
- ),
- );
+ .set_script_fetch_requires_owner_admission(script_preloads_require_owner_admission(
+ &env,
+ ));
state
.buffered_document_preloads
.set_response_csp_requires_parser_admission(
@@ -1164,7 +1156,7 @@ mod tests {
let loader_owner =
ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
let loader = loader_owner.handle();
- let mut state = ParseTimeDriverState::new(final_url);
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(final_url);
let parser_dom_host = state
.parser_session
.stream_handle()
@@ -1421,8 +1413,9 @@ mod tests {
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default())
.expect("test loader should construct");
let mut source = RawDocumentBodySource::External(raw_body);
- let mut state =
- ParseTimeDriverState::new(Url::parse("https://example.test/").expect("test url"));
+ let mut state = ParseTimeDriverState::new_with_scripting_enabled_for_test(
+ Url::parse("https://example.test/").expect("test url"),
+ );
let headers = vec![(
"Content-Type".to_owned(),
"text/html; charset=utf-8".to_owned(),
diff --git a/moli-renderer-v8/src/runtime/script_preloads.rs b/moli-renderer-v8/src/runtime/script_preloads.rs
index f17a652ba..b29ca12d2 100644
--- a/moli-renderer-v8/src/runtime/script_preloads.rs
+++ b/moli-renderer-v8/src/runtime/script_preloads.rs
@@ -46,7 +46,7 @@ pub(super) enum ParserBlockingPreloadDisposition {
pub(super) struct BufferedDocumentPreloadState {
pub(super) entries: DocumentScriptPreloadStore,
document_character_set: String,
- script_fetch_interception_enabled: bool,
+ script_fetch_requires_owner_admission: bool,
response_csp_requires_parser_admission: bool,
owner_wake: Option<RendererOwnerWakeSender>,
resource_task_runner: Option<crate::network::RendererResourceTaskRunner>,
@@ -195,7 +195,7 @@ impl Default for BufferedDocumentPreloadState {
Self {
entries: DocumentScriptPreloadStore::default(),
document_character_set: "UTF-8".to_owned(),
- script_fetch_interception_enabled: false,
+ script_fetch_requires_owner_admission: false,
response_csp_requires_parser_admission: false,
owner_wake: None,
resource_task_runner: None,
@@ -316,7 +316,7 @@ impl BufferedDocumentPreloadState {
loader: &ResourceRequestClient,
service_worker_context: Option<&ServiceWorkerScriptPreloadContext>,
) {
- let requires_owner_admission = self.script_fetch_interception_enabled
+ let requires_owner_admission = self.script_fetch_requires_owner_admission
|| self.response_csp_requires_parser_admission
|| self.meta_csp_preload_gate.has_seen_meta_csp();
let (owner_admitted, legacy_preloads): (Vec<_>, Vec<_>) =
@@ -336,8 +336,8 @@ impl BufferedDocumentPreloadState {
self.document_character_set = document_character_set.to_owned();
}
- pub(super) fn set_script_fetch_interception_enabled(&mut self, enabled: bool) {
- self.script_fetch_interception_enabled = enabled;
+ pub(super) fn set_script_fetch_requires_owner_admission(&mut self, required: bool) {
+ self.script_fetch_requires_owner_admission = required;
}
pub(super) fn set_response_csp_requires_parser_admission(&mut self, required: bool) {
diff --git a/moli-renderer-v8/src/script_vm/dom_inspector.rs b/moli-renderer-v8/src/script_vm/dom_inspector.rs
index 5128f9c15..46fbb95e1 100644
--- a/moli-renderer-v8/src/script_vm/dom_inspector.rs
+++ b/moli-renderer-v8/src/script_vm/dom_inspector.rs
@@ -90,12 +90,13 @@ fn parsed_inspector_attributes(
.unwrap_or(false);
let parsed = if is_html_document {
- HtmlParser.parse_fragment_without_declarative_shadow_roots(
- document_url,
- "http://www.w3.org/1999/xhtml",
- "body",
- markup,
- )
+ HtmlParser::with_scripting_enabled(runtime.document_scripting_enabled(document_handle))
+ .parse_fragment_without_declarative_shadow_roots(
+ document_url,
+ "http://www.w3.org/1999/xhtml",
+ "body",
+ markup,
+ )
} else {
let parsed = XmlParser.parse(document_url, markup);
if !parsed.parse_errors().is_empty() {
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
index 704607bab..747a22eba 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
@@ -25472,7 +25472,7 @@ async fn lightweight_popup_response_csp_sandbox_without_allow_scripts_blocks_inl
"response CSP sandbox popup test server",
"response CSP sandbox popup",
"Content-Security-Policy: sandbox allow-same-origin",
- r#"<!doctype html><script>opener.__popupResponseSandboxScriptEvents.push("script");</script>"#,
+ r#"<!doctype html><script>opener.__popupResponseSandboxScriptEvents.push("script");</script><noscript><span id="popup-response-sandbox-fallback"></span></noscript>"#,
)
.await;
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
@@ -25490,7 +25490,16 @@ async fn lightweight_popup_response_csp_sandbox_without_allow_scripts_blocks_inl
globalThis.__popupResponseSandboxScriptEvents = [];
const popup = open({popup_url_literal});
popup.onload = () => {{
- __popupResponseSandboxScriptEvents.push("load:" + (popup.document.defaultView === popup));
+ const fallback = popup.document.createElement("div");
+ fallback.innerHTML =
+ "<noscript><span id=popup-sandbox-fallback></span></noscript>";
+ (popup.document.body || popup.document.documentElement).appendChild(fallback);
+ __popupResponseSandboxScriptEvents.push([
+ "load",
+ popup.document.defaultView === popup,
+ popup.document.getElementById("popup-response-sandbox-fallback") !== null,
+ popup.document.getElementById("popup-sandbox-fallback") !== null
+ ].join(":"));
}};
return __popupResponseSandboxScriptEvents.length;
}})()
@@ -25519,7 +25528,7 @@ async fn lightweight_popup_response_csp_sandbox_without_allow_scripts_blocks_inl
assert_eq!(
vm.eval("__popupResponseSandboxScriptEvents.join('|')")
.expect("popup response CSP sandbox event log should evaluate"),
- "load:true"
+ "load:true:true:true"
);
}
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs
index 0220021c0..0be21411a 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/detached.rs
@@ -1,5 +1,40 @@
use super::*;
+#[test]
+fn detached_domparser_parses_noscript_with_scripting_disabled() {
+ let mut vm = new_storage_test_vm("https://detached-domparser-noscript.test/");
+
+ let result = vm
+ .eval(
+ r#"
+(() => {
+ const doc = new DOMParser().parseFromString(
+ "<body><noscript><span id='fallback'></span></noscript></body>",
+ "text/html"
+ );
+ const reparsed = doc.createElement("div");
+ reparsed.innerHTML =
+ "<noscript><span id='fragment-fallback'></span></noscript>";
+ doc.body.appendChild(reparsed);
+
+ const created = document.implementation.createHTMLDocument("");
+ created.body.innerHTML =
+ "<noscript><span id='created-fallback'></span></noscript>";
+
+ return [
+ doc.getElementById("fallback") !== null,
+ doc.querySelector("noscript")?.children.length,
+ doc.getElementById("fragment-fallback") !== null,
+ created.getElementById("created-fallback") !== null
+ ].join("|");
+})()
+"#,
+ )
+ .expect("detached DOMParser noscript probe should evaluate");
+
+ assert_eq!(result, "true|1|true|true");
+}
+
#[test]
fn detached_domparser_query_and_element_collections_use_native_handles() {
let mut vm = new_storage_test_vm("https://detached-domparser-query.test/");
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs
index ca2be6d8e..14cda9969 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/dom_surface.rs
@@ -12066,7 +12066,7 @@ fn contextual_fragment_document_element_fragment_append_runs_scripts() {
}
#[test]
-fn sandboxed_contextual_fragment_parses_noscript_when_scripting_disabled() {
+fn sandboxed_fragment_parsers_parse_noscript_when_scripting_disabled() {
let mut vm = new_storage_test_vm("https://sandbox-contextual-fragment-noscript.test/");
let result = vm
@@ -12078,21 +12078,215 @@ fn sandboxed_contextual_fragment_parses_noscript_when_scripting_disabled() {
(document.body || document.documentElement || document).appendChild(iframe);
const doc = iframe.contentDocument;
iframe.contentWindow.didRunScript = false;
- const html =
+ const contextualHtml =
"<script>window.didRunScript = true<\/script>" +
- "<noscript><div id=nos></div>";
- const fragment = doc.createRange().createContextualFragment(html);
+ "<noscript><div id=contextual-nos></div>";
+ const fragment = doc.createRange().createContextualFragment(contextualHtml);
doc.body.appendChild(fragment);
+
+ const inner = doc.createElement("div");
+ inner.innerHTML = "<noscript><div id=inner-nos></div></noscript>";
+ doc.body.appendChild(inner);
+
+ const unsafe = doc.createElement("div");
+ unsafe.setHTMLUnsafe("<noscript><div id=unsafe-nos></div></noscript>");
+ doc.body.appendChild(unsafe);
+
return [
iframe.contentWindow.didRunScript,
- doc.getElementById("nos") !== null
+ doc.getElementById("contextual-nos") !== null,
+ doc.getElementById("inner-nos") !== null,
+ doc.getElementById("unsafe-nos") !== null
].join("|");
})()
"#,
)
- .expect("sandboxed contextual fragment noscript probe should evaluate");
+ .expect("sandboxed fragment noscript probe should evaluate");
+
+ assert_eq!(result, "false|true|true|true");
+}
+
+#[test]
+fn globally_disabled_fragment_parsers_parse_noscript_markup() {
+ let mut vm = new_storage_test_vm("https://disabled-fragment-noscript.test/");
+ vm.set_script_execution_disabled(true);
+
+ let result = vm
+ .eval(
+ r#"
+(() => {
+ const root = document.body || document.documentElement || document;
+ const inner = document.createElement("div");
+ inner.innerHTML = "<noscript><span id=inner-fallback></span></noscript>";
+ root.appendChild(inner);
+
+ const unsafe = document.createElement("div");
+ unsafe.setHTMLUnsafe("<noscript><span id=unsafe-fallback></span></noscript>");
+ root.appendChild(unsafe);
+
+ return [
+ document.getElementById("inner-fallback") !== null,
+ document.getElementById("unsafe-fallback") !== null
+ ].join("|");
+})()
+"#,
+ )
+ .expect("globally disabled fragment noscript probe should evaluate");
+
+ assert_eq!(result, "true|true");
+}
+
+#[test]
+fn response_csp_sandbox_disables_top_document_scripting_semantics() {
+ let mut vm = new_storage_test_vm("https://response-sandbox-noscript.test/");
+ vm.set_response_content_security_policies(&["sandbox".to_owned()]);
+
+ let result = vm
+ .eval(
+ r#"
+(() => {
+ const root = document.body || document.documentElement || document;
+ const inner = document.createElement("div");
+ inner.innerHTML = "<noscript><span id=inner-fallback></span></noscript>";
+ root.appendChild(inner);
+
+ globalThis.__sandboxDynamicScriptRan = false;
+ const script = document.createElement("script");
+ script.textContent = "globalThis.__sandboxDynamicScriptRan = true";
+ root.appendChild(script);
+
+ globalThis.__sandboxHandlerRan = false;
+ const button = document.createElement("button");
+ button.setAttribute("onclick", "globalThis.__sandboxHandlerRan = true");
+ root.appendChild(button);
+ button.click();
+
+ const beforeOpen = [
+ document.getElementById("inner-fallback") !== null,
+ globalThis.__sandboxDynamicScriptRan,
+ globalThis.__sandboxHandlerRan
+ ];
+
+ document.open();
+ document.write(
+ "<!doctype html><noscript><main id=document-write-fallback></main></noscript>"
+ );
+ document.close();
+ return beforeOpen.concat(
+ document.getElementById("document-write-fallback") !== null
+ ).join("|");
+})()
+"#,
+ )
+ .expect("response CSP sandbox scripting probe should evaluate");
+
+ assert_eq!(result, "true|false|false|true");
+}
+
+#[tokio::test]
+async fn detached_frame_tree_snapshot_reuses_each_child_document_scripting_policy() {
+ let mut enabled_vm = new_storage_test_vm("https://enabled-detached-frame-tree-noscript.test/");
+
+ enabled_vm
+ .eval(
+ r#"
+(() => {
+ const root = document.body || document.documentElement || document;
+ const frame = document.createElement("iframe");
+ frame.id = "enabled";
+ frame.srcdoc =
+ '<noscript><base href="https://enabled-fallback-base.test/"><iframe id="enabled-fallback" name="enabled-fallback"></iframe></noscript>';
+ root.appendChild(frame);
+})()
+"#,
+ )
+ .expect("scripting-enabled detached frame-tree fixture should evaluate");
+ expect_one_child_frame_task_source(
+ &mut enabled_vm,
+ ChildFrameSemanticTurnKind::NavigationCommit,
+ "enabled srcdoc commit",
+ )
+ .await;
+
+ let enabled_handle = enabled_vm
+ .document_runtime
+ .dom_host()
+ .element_handle_by_id("enabled")
+ .expect("scripting-enabled iframe owner");
+ assert_ne!(
+ enabled_vm
+ ._context_host
+ .borrow()
+ .child_browsing_context_base_url(enabled_handle)
+ .as_ref()
+ .map(Url::as_str),
+ Some("https://enabled-fallback-base.test/"),
+ "scripting-enabled noscript contents must not install a fallback base element"
+ );
+ let enabled_tree = enabled_vm.child_browsing_context_frame_tree_snapshot_for_protocol();
+ assert_eq!(enabled_tree.len(), 1);
+ assert!(
+ enabled_tree[0].child_frames.is_empty(),
+ "scripting-enabled noscript contents must remain text in snapshot fallback parsing"
+ );
- assert_eq!(result, "false|true");
+ let mut sandboxed_vm =
+ new_storage_test_vm("https://sandboxed-detached-frame-tree-noscript.test/");
+ sandboxed_vm
+ .eval(
+ r#"
+(() => {
+ const root = document.body || document.documentElement || document;
+ const frame = document.createElement("iframe");
+ frame.id = "sandboxed";
+ frame.setAttribute("sandbox", "allow-same-origin");
+ frame.srcdoc =
+ '<noscript><base href="https://sandboxed-fallback-base.test/"><iframe id="sandboxed-fallback" name="sandboxed-fallback"></iframe></noscript>';
+ root.appendChild(frame);
+})()
+"#,
+ )
+ .expect("sandboxed detached frame-tree fixture should evaluate");
+ expect_one_child_frame_task_source(
+ &mut sandboxed_vm,
+ ChildFrameSemanticTurnKind::NavigationCommit,
+ "sandboxed srcdoc commit",
+ )
+ .await;
+
+ let sandboxed_handle = sandboxed_vm
+ .document_runtime
+ .dom_host()
+ .element_handle_by_id("sandboxed")
+ .expect("sandboxed iframe owner");
+ assert_eq!(
+ sandboxed_vm
+ ._context_host
+ .borrow()
+ .child_browsing_context_base_url(sandboxed_handle)
+ .as_ref()
+ .map(Url::as_str),
+ Some("https://sandboxed-fallback-base.test/"),
+ "script-disallowed noscript contents must contribute their base element"
+ );
+ let sandboxed_tree = sandboxed_vm.child_browsing_context_frame_tree_snapshot_for_protocol();
+ assert_eq!(sandboxed_tree.len(), 1);
+ assert_eq!(
+ sandboxed_tree[0]
+ .child_frames
+ .iter()
+ .map(|frame| frame.owner_element_id.as_deref())
+ .collect::<Vec<_>>(),
+ vec![Some("sandboxed-fallback")],
+ "script-disallowed noscript contents must remain markup in snapshot fallback parsing"
+ );
+ let nested_frame_id = sandboxed_tree[0].child_frames[0].frame_id.clone();
+ assert!(
+ sandboxed_vm
+ .child_browsing_context_document_snapshot_by_frame_id(&nested_frame_id)
+ .is_some(),
+ "frame-id lookup must use the same scripting-disabled snapshot parser"
+ );
}
#[test]
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index 940d8c604..d07fabe4a 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -593,7 +593,8 @@ fn new_parsed_page_task_executor_test_vm(
markup: &str,
loader: &ResourceRequestClient,
) -> crate::runtime::PageVmTaskExecutorTestHarness {
- let document = HtmlParser.parse(Url::parse(url).expect("test URL"), markup.to_owned());
+ let document =
+ HtmlParser::SCRIPTING_ENABLED.parse(Url::parse(url).expect("test URL"), markup.to_owned());
let page = crate::runtime::PageVmTaskExecutorTestHarness::new_with_dom_host(
DomHost::from_dom(document),
loader,
@@ -606,7 +607,8 @@ fn new_streamed_parser_page_task_executor_test_vm(
markup: &str,
loader: &ResourceRequestClient,
) -> crate::runtime::PageVmTaskExecutorTestHarness {
- let mut stream = HtmlParser.start_document(Url::parse(url).expect("test URL"));
+ let mut stream =
+ HtmlParser::SCRIPTING_ENABLED.start_document(Url::parse(url).expect("test URL"));
stream.feed(markup);
let page = crate::runtime::PageVmTaskExecutorTestHarness::new_with_dom_host(
stream.take_parser_stream_dom_host(),
@@ -13952,7 +13954,8 @@ async fn main_document_replacement_retires_pending_media_and_text_track_sequence
fn new_parsed_test_vm(url: &str, markup: &str) -> StandaloneScriptVmHarness {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(Url::parse(url).expect("test url"), markup.to_owned());
+ let document =
+ HtmlParser::SCRIPTING_ENABLED.parse(Url::parse(url).expect("test url"), markup.to_owned());
let page_task_queue = crate::page_task_queue::PageTaskQueueTestHarness::new();
let post_domcontentloaded_page_task_sender =
page_task_queue.owner_attached_runtime_page_task_sender_for_test();
@@ -13982,7 +13985,8 @@ fn new_parsed_test_vm_with_loader_and_resource_completion_queue(
RendererResourceCompletionTestHarness,
) {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(Url::parse(url).expect("test url"), markup.to_owned());
+ let document =
+ HtmlParser::SCRIPTING_ENABLED.parse(Url::parse(url).expect("test url"), markup.to_owned());
let page_task_queue = crate::page_task_queue::PageTaskQueueTestHarness::new();
let post_domcontentloaded_page_task_sender =
page_task_queue.owner_attached_runtime_page_task_sender_for_test();
@@ -14171,7 +14175,8 @@ async fn in_flight_connected_modulepreload_does_not_delay_window_load() {
fn new_streamed_parser_test_vm(url: &str, markup: &str) -> StandaloneScriptVmHarness {
let _js_runtime = crate::JsRuntime::initialize();
- let mut stream = HtmlParser.start_document(Url::parse(url).expect("test url"));
+ let mut stream =
+ HtmlParser::SCRIPTING_ENABLED.start_document(Url::parse(url).expect("test url"));
stream.feed(markup);
let dom_host = stream.take_parser_stream_dom_host();
let page_task_queue = crate::page_task_queue::PageTaskQueueTestHarness::new();
diff --git a/moli-renderer-v8/src/script_vm/tests/post_parse.rs b/moli-renderer-v8/src/script_vm/tests/post_parse.rs
index 32fd6dae6..8d01cf095 100644
--- a/moli-renderer-v8/src/script_vm/tests/post_parse.rs
+++ b/moli-renderer-v8/src/script_vm/tests/post_parse.rs
@@ -21,7 +21,7 @@ fn prepared_post_parse_script(position: usize, mode: ScriptMode) -> PreparedScri
ScriptMode::Normal => "",
other => panic!("unsupported test script mode: {other:?}"),
};
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").expect("test url"),
format!(
"<!doctype html><html><head><script{attribute} src=\"/script-{position}.js\"></script></head><body></body></html>"
@@ -373,7 +373,7 @@ fn module_graph_redirect_final_url_obeys_script_src_csp() {
#[tokio::test]
async fn external_module_prepared_script_hides_root_graph_fetch_in_owner_state() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/page.html").expect("test url"),
"<!doctype html><html><head><script type=\"module\" src=\"/entry\"></script></head></html>"
.to_owned(),
@@ -1075,7 +1075,7 @@ async fn page_timer_turn_propagates_host_driver_failure() {
#[tokio::test]
async fn post_parse_round_injects_lifecycle_boundary_tasks_around_trailing_work() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -2191,7 +2191,7 @@ fn session_storage_does_not_cross_browsing_context_handle_boundaries() {
async fn poll_next_post_parse_driver_step_requests_wait_when_owner_progress_is_pending_but_not_ready()
{
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href='/app.css'></head><body></body></html>"
.to_owned(),
@@ -2236,7 +2236,7 @@ async fn poll_next_post_parse_driver_step_requests_wait_when_owner_progress_is_p
#[tokio::test]
async fn poll_next_post_parse_driver_step_prefers_owner_action_over_runtime_continuation() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><link rel=stylesheet href='/app.css'></head><body></body></html>"
.to_owned(),
@@ -2299,7 +2299,7 @@ async fn poll_next_post_parse_driver_step_prefers_owner_action_over_runtime_cont
async fn poll_next_post_parse_driver_step_requests_wait_for_runtime_backlog_without_owner_progress()
{
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -2529,7 +2529,7 @@ fn post_parse_lifecycle_driver_idle_completion_preserves_round_stats() {
#[tokio::test]
async fn next_post_parse_lifecycle_advance_from_driver_returns_complete_when_driver_is_idle() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -2575,7 +2575,7 @@ async fn next_post_parse_lifecycle_advance_from_driver_returns_complete_when_dri
async fn next_post_parse_lifecycle_advance_from_driver_returns_page_owned_task_for_ready_processing_action()
{
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -2630,7 +2630,7 @@ async fn next_post_parse_lifecycle_advance_from_driver_returns_page_owned_task_f
#[tokio::test]
async fn finish_completed_post_parse_page_owned_task_or_continue_returns_boundary_completion() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -2681,7 +2681,7 @@ async fn finish_completed_post_parse_page_owned_task_or_continue_returns_boundar
#[tokio::test]
async fn advance_post_parse_lifecycle_returns_completion_from_completed_boundary_task() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -2741,7 +2741,7 @@ async fn advance_post_parse_lifecycle_returns_completion_from_completed_boundary
#[tokio::test]
async fn advance_post_parse_lifecycle_continues_to_driver_after_non_boundary_completion() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -2808,7 +2808,7 @@ async fn advance_post_parse_lifecycle_continues_to_driver_after_non_boundary_com
async fn advance_post_parse_lifecycle_restarts_invalidated_round_after_completed_task_before_returning_task()
{
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -2870,7 +2870,7 @@ async fn advance_post_parse_lifecycle_restarts_invalidated_round_after_completed
#[tokio::test]
async fn advance_post_parse_lifecycle_restarts_invalidated_round_before_boundary_completion() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -2994,7 +2994,7 @@ async fn prepare_post_parse_task_execution_restarts_restartable_task_after_inval
#[test]
fn poll_next_post_parse_driver_step_returns_idle_without_owner_or_runtime_work() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3041,7 +3041,7 @@ fn runtime_script_work_pause_tracks_internal_pause_kind() {
#[test]
fn selected_post_parse_action_settlement_publishes_concrete_runtime_followup() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3078,7 +3078,7 @@ fn selected_post_parse_action_settlement_publishes_concrete_runtime_followup() {
#[test]
fn selected_post_parse_action_settlement_arms_stable_continuation_state() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3127,7 +3127,7 @@ fn selected_post_parse_action_settlement_arms_stable_continuation_state() {
fn runtime_owned_module_source_ready_before_domcontentloaded_publishes_task_without_starting_graph_inline()
{
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3189,7 +3189,7 @@ fn runtime_owned_module_source_ready_before_domcontentloaded_publishes_task_with
#[test]
fn explicitly_domcontentloaded_gated_runtime_head_is_not_admitted_early() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3257,7 +3257,7 @@ fn explicitly_domcontentloaded_gated_runtime_head_is_not_admitted_early() {
#[tokio::test]
async fn reentrant_runtime_admission_survives_page_task_claim_in_stable_authority() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3447,7 +3447,7 @@ async fn reentrant_runtime_admission_survives_page_task_claim_in_stable_authorit
#[test]
fn script_terminal_event_body_defers_listener_reaction_to_task_completion() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3525,7 +3525,7 @@ fn script_terminal_event_body_defers_listener_reaction_to_task_completion() {
#[test]
fn runtime_dynamic_script_terminal_consumes_its_accepted_document_lease_inline() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3646,7 +3646,7 @@ fn runtime_dynamic_script_terminal_consumes_its_accepted_document_lease_inline()
#[test]
fn runtime_owned_inline_importmap_bypasses_dcl_gate() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3707,7 +3707,7 @@ fn runtime_owned_inline_importmap_bypasses_dcl_gate() {
#[test]
fn followup_task_boundary_preserves_pending_dynamic_source_residence() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3747,7 +3747,7 @@ fn followup_task_boundary_preserves_pending_dynamic_source_residence() {
#[tokio::test]
async fn queued_pre_domcontentloaded_runtime_tasks_are_backfilled_ahead_of_domcontentloaded() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3805,7 +3805,7 @@ async fn queued_pre_domcontentloaded_runtime_tasks_are_backfilled_ahead_of_domco
#[test]
fn selected_post_parse_action_keeps_pending_dynamic_source_out_of_pre_dcl_lane_after_dcl() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3850,7 +3850,7 @@ fn selected_post_parse_action_keeps_pending_dynamic_source_out_of_pre_dcl_lane_a
#[test]
fn post_parse_owner_readiness_does_not_block_window_load_for_generic_post_dcl_pause_state() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head></head><body></body></html>".to_owned(),
);
@@ -3887,7 +3887,7 @@ fn post_parse_owner_readiness_does_not_block_window_load_for_generic_post_dcl_pa
#[test]
fn document_write_owned_inline_normal_defers_already_started_until_execution_without_handle() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><head><script>window.test = 1;</script></head><body></body></html>"
.to_owned(),
@@ -3950,7 +3950,7 @@ fn document_write_owned_inline_normal_defers_already_started_until_execution_wit
#[test]
fn script_inner_text_exposes_inline_json_payload() {
let _js_runtime = crate::JsRuntime::initialize();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.com/").unwrap(),
"<!doctype html><html><body><script id=\"RENDER_DATA\" type=\"application/json\">%7B%22data%22%3A1%7D</script></body></html>"
.to_owned(),
diff --git a/moli-renderer-v8/src/stylesheet_runtime/completion.rs b/moli-renderer-v8/src/stylesheet_runtime/completion.rs
index 0adc4d779..f0e9c415d 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/completion.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/completion.rs
@@ -358,7 +358,7 @@ mod tests {
client_count,
)
.collect::<String>();
- let document = HtmlParser.parse(
+ let document = HtmlParser::SCRIPTING_ENABLED.parse(
Url::parse("https://example.test/page").unwrap(),
format!("<!doctype html><html><head>{links}</head><body></body></html>"),
);
diff --git a/moli-renderer-v8/src/stylesheet_runtime/connected.rs b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
index 715958b7d..21264036b 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/connected.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
@@ -832,6 +832,24 @@ impl DocumentRuntime {
let resource_type = element
.map(preload_like_link_resource_type)
.unwrap_or(SubresourceResourceType::Fetch);
+ let is_modulepreload =
+ self.connected_owner_uses_non_blocking_modulepreload_identity(handle);
+ if !self.document_scripting_enabled()
+ && (is_modulepreload || resource_type == SubresourceResourceType::Script)
+ {
+ // Script-disabled Documents do not even fetch page-authored
+ // preload/modulepreload resources. Release any load-event
+ // lease without posting a synthetic terminal event.
+ self.stylesheet_lifecycle
+ .owner_states
+ .clear_async_operations(handle);
+ self.settle_connected_style_load_admission(
+ host_ptr,
+ event_admission,
+ "script execution disabled",
+ );
+ return result;
+ }
if let Some((key, preload)) = self.connected_modulepreload_request(handle, &url) {
let unchanged = self
.stylesheet_lifecycle
@@ -2309,7 +2327,7 @@ mod tests {
#[test]
fn blocked_csp_disposition_does_not_hide_initial_style_error_task() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><style>body { color: red }</style></head></html>"
@@ -2527,7 +2545,7 @@ mod tests {
#[test]
fn native_module_source_completion_marks_modulepreload_script_link_ready() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"modulepreload\" href=\"/app.mjs\"></head><body></body></html>"
@@ -2563,7 +2581,7 @@ mod tests {
#[test]
fn native_module_failure_completion_marks_modulepreload_script_link_ready_for_error() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"modulepreload\" href=\"/app.mjs\"></head><body></body></html>"
@@ -2601,7 +2619,7 @@ mod tests {
#[test]
fn native_module_completion_marks_css_modulepreload_link_ready_when_as_style() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"modulepreload\" href=\"/style.css\" as=\"style\"></head><body></body></html>"
@@ -2640,7 +2658,7 @@ mod tests {
#[test]
fn implicit_css_suffix_modulepreload_keeps_its_captured_javascript_key() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"modulepreload\" href=\"/style.css\"></head><body></body></html>"
@@ -2675,7 +2693,7 @@ mod tests {
#[test]
fn stale_same_key_native_modulepreload_client_cannot_complete_new_processing() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=modulepreload href=/same.mjs></head><body></body></html>"
@@ -2714,7 +2732,7 @@ mod tests {
#[test]
fn posted_native_modulepreload_event_keeps_accepted_client_after_reprocess() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=modulepreload href=/same.mjs></head><body></body></html>"
@@ -2747,7 +2765,7 @@ mod tests {
#[test]
fn connected_modulepreload_script_link_returns_owner_start() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"modulepreload\" href=\"/app.mjs\"></head><body></body></html>"
@@ -2806,9 +2824,38 @@ mod tests {
Ok(())
}
+ #[test]
+ fn script_disabled_document_does_not_start_connected_script_preloads() -> Result<()> {
+ let parser = HtmlParser::SCRIPTING_ENABLED;
+ let document = parser.parse(
+ Url::parse("https://example.test/page").unwrap(),
+ concat!(
+ "<!doctype html><html><head>",
+ "<link rel='preload' as='script' href='/classic.js'>",
+ "<link rel='modulepreload' href='/module.mjs'>",
+ "</head><body></body></html>",
+ )
+ .to_owned(),
+ );
+ let mut runtime = DocumentRuntime::new(&document);
+ runtime.set_script_execution_disabled(true);
+
+ runtime.queue_initial_connected_style_loads();
+ let (starts, warnings) = runtime.prime_pending_connected_style_loads().into_parts();
+
+ assert!(starts.is_empty());
+ assert!(warnings.is_empty());
+ assert!(
+ !runtime.has_pending_style_loads(),
+ "inert script preloads must not retain load-event or module-map work"
+ );
+ assert!(runtime.pop_ready_connected_style_load().is_none());
+ Ok(())
+ }
+
#[test]
fn connected_modulepreload_supported_as_values_return_owner_starts() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
concat!(
@@ -2861,7 +2908,7 @@ mod tests {
#[test]
fn connected_modulepreload_as_values_match_wpt_matrix() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
modulepreload_as_matrix_markup(),
@@ -2923,7 +2970,7 @@ mod tests {
#[test]
fn connected_modulepreload_ignores_fetchpriority_hint() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
concat!(
@@ -2954,7 +3001,7 @@ mod tests {
#[test]
fn connected_modulepreload_skips_non_matching_media() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
concat!(
@@ -2999,7 +3046,7 @@ mod tests {
#[test]
fn connected_modulepreload_invalid_as_records_warning_and_error_event() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"modulepreload\" href=\"/bad.bin\" as=\"image\"></head><body></body></html>"
@@ -3039,7 +3086,7 @@ mod tests {
#[tokio::test(flavor = "current_thread")]
async fn connected_modulepreload_start_survives_installed_loader_fast_path() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"modulepreload\" href=\"/app.mjs\"></head><body></body></html>"
@@ -3064,7 +3111,7 @@ mod tests {
#[tokio::test(flavor = "current_thread")]
async fn connected_modulepreload_invalid_as_warning_survives_installed_loader_fast_path()
-> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"modulepreload\" href=\"/bad.bin\" as=\"image\"></head><body></body></html>"
@@ -3095,7 +3142,7 @@ mod tests {
#[test]
fn connected_modulepreload_script_link_reuses_fetched_module_map_entry() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"modulepreload\" href=\"/app.mjs\"></head><body></body></html>"
@@ -3153,7 +3200,7 @@ mod tests {
#[test]
fn processed_inline_source_ignores_imports_after_style_rules() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><style>.ready { color: green; } @import url('/late.css');</style></head><body></body></html>"
@@ -3173,7 +3220,7 @@ mod tests {
#[test]
fn processed_inline_source_allows_charset_before_imports() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><style>@charset \"utf-8\"; @import url('/early.css'); .ready { color: green; }</style></head><body></body></html>"
@@ -3193,7 +3240,7 @@ mod tests {
#[test]
fn processed_inline_source_deduplicates_imports_in_document_order() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
concat!(
@@ -3223,7 +3270,7 @@ mod tests {
#[test]
fn blocking_stylesheet_promotion_leaves_independent_style_import_operation_pending() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><style>@import url('/runtime.css');</style></head><body></body></html>"
@@ -3280,7 +3327,7 @@ mod tests {
#[tokio::test]
async fn data_stylesheet_link_with_failed_import_queues_error_event() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
concat!(
@@ -3329,7 +3376,7 @@ mod tests {
#[test]
fn connected_style_data_import_without_nested_import_queues_load_event() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
concat!(
@@ -3361,7 +3408,7 @@ mod tests {
#[test]
fn connected_style_data_import_failure_queues_error_event() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
concat!(
@@ -3393,7 +3440,7 @@ mod tests {
#[test]
fn modulepreload_link_readiness_uses_module_script_credentials() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"modulepreload\" href=\"/app.mjs\" crossorigin=\"use-credentials\"></head><body></body></html>"
@@ -3415,7 +3462,7 @@ mod tests {
#[test]
fn anonymous_modulepreload_link_readiness_uses_same_origin_credentials() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"modulepreload\" href=\"/app.mjs\" crossorigin=\"anonymous\"></head><body></body></html>"
@@ -3497,7 +3544,7 @@ mod tests {
#[tokio::test]
async fn image_preload_link_becomes_ready_without_network_when_image_fetch_disabled()
-> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"preload\" as=\"image\" href=\"http://127.0.0.1:9/image.png\"></head><body></body></html>"
@@ -3532,7 +3579,7 @@ mod tests {
#[test]
fn font_preload_link_readiness_tracks_font_type_and_priority_hint() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"preload\" as=\"font\" href=\"/font.woff2\" fetchpriority=\"high\"></head><body></body></html>"
@@ -3549,7 +3596,7 @@ mod tests {
#[tokio::test]
async fn style_preload_request_attribute_change_replaces_exact_client_and_fetch() -> Result<()>
{
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=preload as=style href='http://127.0.0.1:9/a.css' crossorigin=anonymous></head><body></body></html>"
@@ -3622,7 +3669,7 @@ mod tests {
#[tokio::test]
async fn stylesheet_and_modulepreload_switches_drop_stale_event_bindings() -> Result<()> {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=preload as=style href='http://127.0.0.1:9/shared'></head><body></body></html>"
@@ -3719,7 +3766,7 @@ mod tests {
#[test]
fn media_preload_link_readiness_tracks_audio_and_video_types() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
concat!(
@@ -3763,7 +3810,7 @@ mod tests {
#[test]
fn late_style_preload_link_readiness_uses_medium_stylesheet_request_type() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"preload\" as=\"style\" href=\"/late.css\"></head><body></body></html>"
@@ -3794,7 +3841,7 @@ mod tests {
#[test]
fn initial_scan_marks_preload_stylesheet_after_first_image_as_late() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
concat!(
@@ -3819,7 +3866,7 @@ mod tests {
#[test]
fn parser_created_non_blocking_media_stylesheet_waits_for_initial_scan() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"stylesheet\" media=\"print\" href=\"/print.css\"></head><body></body></html>"
@@ -3850,7 +3897,7 @@ mod tests {
#[test]
fn parser_created_style_element_waits_for_initial_scan() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><style>@import url('/missing.css');</style></head><body></body></html>"
@@ -3881,7 +3928,7 @@ mod tests {
#[test]
fn initial_scan_does_not_repeat_a_previously_processed_connected_style() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><style>body { color: red; }</style></head><body></body></html>"
@@ -3924,7 +3971,7 @@ mod tests {
#[tokio::test]
async fn parser_roundtrip_does_not_reschedule_connected_style_event() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"stylesheet\" href=\"data:text/css,body{}\"></head><body></body></html>"
@@ -4025,7 +4072,7 @@ mod tests {
#[tokio::test]
async fn cached_stylesheet_fetch_admission_posts_event_without_another_network_terminal() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let href = "data:text/css,body{}";
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
@@ -4218,7 +4265,7 @@ mod tests {
});
let document_url = Url::parse(&format!("http://{addr}/page.html")).unwrap();
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
document_url,
"<!doctype html><html><head>\
@@ -4306,7 +4353,7 @@ mod tests {
#[tokio::test]
async fn completed_style_preload_admits_late_stylesheet_install_client() {
let href = "data:text/css,.late%7Bcolor%3Agreen%7D";
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
format!(
@@ -4369,7 +4416,7 @@ mod tests {
#[tokio::test]
async fn completed_stylesheet_admits_late_preload_event_only_client() {
let href = "data:text/css,.first%7Bcolor%3Agreen%7D";
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
format!(
@@ -4425,7 +4472,7 @@ mod tests {
#[test]
fn prefetch_link_readiness_uses_fetch_cdp_type_and_link_prefetch_request_type() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"prefetch\" as=\"image\" href=\"/next.png\"></head><body></body></html>"
@@ -4445,7 +4492,7 @@ mod tests {
#[test]
fn fetch_preload_link_readiness_uses_fetch_cdp_type_and_raw_request_type() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"preload\" as=\"fetch\" href=\"/data.json\"></head><body></body></html>"
@@ -4466,7 +4513,7 @@ mod tests {
#[test]
fn crossorigin_fetch_preload_link_readiness_uses_cors_mode() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
concat!(
@@ -4516,7 +4563,7 @@ mod tests {
#[test]
fn style_preload_link_without_crossorigin_uses_no_cors_request_parameters() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"preload\" as=\"style\" href=\"/style.css\"></head><body></body></html>"
@@ -4547,7 +4594,7 @@ mod tests {
#[test]
fn anonymous_style_preload_uses_cors_request_parameters() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"preload\" as=\"style\" href=\"/style.css\" crossorigin=\"anonymous\"></head><body></body></html>"
@@ -4578,7 +4625,7 @@ mod tests {
#[test]
fn compression_dictionary_link_readiness_uses_other_cdp_type_and_dictionary_request_type() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"compression-dictionary\" href=\"/dict.bin\"></head><body></body></html>"
@@ -4600,7 +4647,7 @@ mod tests {
#[test]
fn connected_style_load_handles_include_prefetch_links() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"prefetch\" href=\"/next.html\"></head><body></body></html>"
@@ -4625,7 +4672,7 @@ mod tests {
#[test]
fn connected_style_load_handles_include_compression_dictionary_links() {
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let document = parser.parse(
Url::parse("https://example.test/page").unwrap(),
"<!doctype html><html><head><link rel=\"compression-dictionary\" href=\"/dict.bin\"></head><body></body></html>"
diff --git a/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs b/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs
index 0dd1a635c..44a0ccbed 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs
@@ -509,7 +509,7 @@ mod tests {
#[tokio::test]
async fn invalidated_blocking_transport_can_release_the_shared_graph() {
let document_url = Url::parse("https://example.test/page").unwrap();
- let parser = HtmlParser;
+ let parser = HtmlParser::SCRIPTING_ENABLED;
let first_document = parser.parse(
document_url.clone(),
"<!doctype html><style>@import url('data:text/css,.first%7Bcolor:red%7D');</style>"
diff --git a/moli/src/cli.rs b/moli/src/cli.rs
index 863df6f19..6c095e797 100644
--- a/moli/src/cli.rs
+++ b/moli/src/cli.rs
@@ -47,6 +47,14 @@ pub struct FetchArgs {
#[arg(short = 'H', long = "header", value_name = "HEADER", value_parser = parse_request_header_arg)]
pub headers: Vec<RequestHeaderArg>,
+ /// Disable page-authored JavaScript before the Document starts parsing.
+ /// Stylesheets still load; automation expressions remain available.
+ #[arg(
+ long,
+ conflicts_with_all = ["document_start_script", "document_start_script_file"]
+ )]
+ pub disable_js: bool,
+
#[arg(long)]
pub with_base: bool,
diff --git a/moli/src/config.rs b/moli/src/config.rs
index 53c972938..df3bd024d 100644
--- a/moli/src/config.rs
+++ b/moli/src/config.rs
@@ -41,6 +41,9 @@ impl AppConfig {
.iter()
.map(|header| (header.name.clone(), header.value.clone()))
.collect();
+ config
+ .browser
+ .set_script_execution_disabled(args.disable_js);
config.fetch.dump_mode = args.dump;
config.fetch.strip = args.strip_options();
config.fetch.with_base = args.with_base;
diff --git a/moli/tests/cli.rs b/moli/tests/cli.rs
index 6110ac713..51feab2cf 100644
--- a/moli/tests/cli.rs
+++ b/moli/tests/cli.rs
@@ -34,6 +34,7 @@ fn parses_explicit_fetch_command_with_compatibility_flags() {
"X-Test: one",
"-H",
"X-Trace: two",
+ "--disable-js",
"--with-base",
"--with-frames",
"--strip-mode",
@@ -83,6 +84,7 @@ fn parses_explicit_fetch_command_with_compatibility_flags() {
value: "two".to_owned(),
},
],
+ disable_js: true,
with_base: true,
with_frames: true,
trace_network: false,
@@ -415,6 +417,7 @@ fn infers_fetch_mode_from_bare_url() {
Commands::Fetch(Box::new(FetchArgs {
dump: None,
headers: vec![],
+ disable_js: false,
with_base: false,
with_frames: false,
trace_network: false,
@@ -454,6 +457,7 @@ fn parses_bare_dump_with_explicit_fetch_command_and_defaults_to_html() {
Commands::Fetch(Box::new(FetchArgs {
dump: Some(DumpFormat::Html),
headers: vec![],
+ disable_js: false,
with_base: false,
with_frames: false,
trace_network: false,
@@ -497,6 +501,7 @@ fn parses_header_flag_with_explicit_fetch_command() {
name: "X-Test".to_owned(),
value: "one".to_owned(),
}],
+ disable_js: false,
with_base: false,
with_frames: false,
trace_network: false,
@@ -884,6 +889,23 @@ fn fetch_strip_options_combine_cli_selections() {
);
}
+#[test]
+fn disable_js_rejects_document_start_script_injection() {
+ for injection in ["--document-start-script", "--document-start-script-file"] {
+ let error = Cli::try_parse_from(normalize_args_for_compat([
+ "moli",
+ "fetch",
+ "--disable-js",
+ injection,
+ "fixture.js",
+ "https://example.com",
+ ]))
+ .unwrap_err();
+
+ assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
+ }
+}
+
#[test]
fn rejects_removed_noscript_flag() {
let error = Cli::try_parse_from(normalize_args_for_compat([
@@ -1321,6 +1343,36 @@ fn app_config_from_fetch_cli_enables_image_fetch() {
assert!(config.browser.image_fetch_enabled());
}
+#[test]
+fn app_config_from_fetch_cli_disables_script_execution_only_when_requested() {
+ let enabled = Cli::try_parse_from(normalize_args_for_compat([
+ "moli",
+ "fetch",
+ "https://example.com",
+ ]))
+ .unwrap();
+ assert!(
+ !AppConfig::from_cli(&enabled)
+ .unwrap()
+ .browser
+ .script_execution_disabled()
+ );
+
+ let disabled = Cli::try_parse_from(normalize_args_for_compat([
+ "moli",
+ "fetch",
+ "--disable-js",
+ "https://example.com",
+ ]))
+ .unwrap();
+ assert!(
+ AppConfig::from_cli(&disabled)
+ .unwrap()
+ .browser
+ .script_execution_disabled()
+ );
+}
+
#[test]
fn app_config_from_serve_cli_enables_image_fetch() {
let cli = Cli::try_parse_from(normalize_args_for_compat(["moli", "serve", "--image"])).unwrap();
diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rs
index 08174815e..89ad96702 100644
--- a/moli/tests/fetch_cli.rs
+++ b/moli/tests/fetch_cli.rs
@@ -34,6 +34,9 @@ use support::FixtureServer;
use tokio::{io::AsyncReadExt, net::TcpListener, task::JoinHandle};
use tracing_subscriber::fmt::MakeWriter;
+#[path = "fetch_cli/disable_js.rs"]
+mod disable_js;
+
struct Output {
status: OutputStatus,
stdout: Vec<u8>,
diff --git a/moli/tests/fetch_cli/disable_js.rs b/moli/tests/fetch_cli/disable_js.rs
new file mode 100644
index 000000000..80cd8f933
--- /dev/null
+++ b/moli/tests/fetch_cli/disable_js.rs
@@ -0,0 +1,689 @@
+use super::{Output, clean_output, run_fetch_cli_with_args};
+use anyhow::Result;
+use axum::{
+ Router,
+ extract::State,
+ http::{StatusCode, Uri},
+ response::{Html, IntoResponse, Response},
+ routing::get,
+};
+use parking_lot::Mutex;
+use std::sync::Arc;
+use tokio::{net::TcpListener, task::JoinHandle};
+
+const STYLESHEET_PATHS: [&str; 7] = [
+ "/main.css",
+ "/noscript.css",
+ "/imported.css",
+ "/child.css",
+ "/grandchild.css",
+ "/srcdoc.css",
+ "/srcdoc-noscript.css",
+];
+const SCRIPT_PATHS: [&str; 16] = [
+ "/initial.js",
+ "/preload.js",
+ "/module-preload.js",
+ "/classic.js",
+ "/defer.js",
+ "/async.js",
+ "/module.js",
+ "/child-preload.js",
+ "/child.js",
+ "/grandchild-preload.js",
+ "/grandchild.js",
+ "/srcdoc-preload.js",
+ "/srcdoc.js",
+ "/dynamic.js",
+ "/child-dynamic.js",
+ "/document-write.js",
+];
+
+const DISABLED_READY_SCRIPT: &str = r#"(() => {
+ const fallback = document.getElementById('fallback');
+ const styled = document.getElementById('styled');
+ const child = document.getElementById('child')?.contentDocument;
+ const childFallback = child?.getElementById('child-fallback');
+ const grandchild = child?.getElementById('grandchild')?.contentDocument;
+ const grandchildFallback = grandchild?.getElementById('grandchild-fallback');
+ const srcdoc = document.getElementById('srcdoc-child')?.contentDocument;
+ const srcdocFallback = srcdoc?.getElementById('srcdoc-fallback');
+ const ready = Boolean(
+ fallback &&
+ styled &&
+ childFallback &&
+ grandchildFallback &&
+ srcdocFallback &&
+ getComputedStyle(fallback).color === 'rgb(1, 2, 3)' &&
+ getComputedStyle(fallback).backgroundColor === 'rgb(4, 5, 6)' &&
+ getComputedStyle(styled).color === 'rgb(7, 8, 9)' &&
+ child.defaultView.getComputedStyle(childFallback).color === 'rgb(10, 11, 12)' &&
+ grandchild.defaultView.getComputedStyle(grandchildFallback).color === 'rgb(13, 14, 15)' &&
+ srcdoc.defaultView.getComputedStyle(srcdocFallback).color === 'rgb(16, 17, 18)' &&
+ srcdoc.defaultView.getComputedStyle(srcdocFallback).backgroundColor === 'rgb(19, 20, 21)' &&
+ !document.documentElement.hasAttribute('data-inline-script') &&
+ !document.documentElement.hasAttribute('data-external-script') &&
+ !child.documentElement.hasAttribute('data-child-inline-script') &&
+ !child.documentElement.hasAttribute('data-external-script') &&
+ !grandchild.documentElement.hasAttribute('data-grandchild-inline-script') &&
+ !grandchild.documentElement.hasAttribute('data-external-script') &&
+ !srcdoc.documentElement.hasAttribute('data-srcdoc-inline-script') &&
+ !srcdoc.documentElement.hasAttribute('data-external-script')
+ );
+ if (ready) {
+ document.documentElement.setAttribute('data-disable-js-probe', 'ready');
+ }
+ return ready;
+})()"#;
+
+const ENABLED_READY_SCRIPT: &str = r#"(() => {
+ const child = document.getElementById('child')?.contentDocument;
+ const grandchild = child?.getElementById('grandchild')?.contentDocument;
+ const srcdoc = document.getElementById('srcdoc-child')?.contentDocument;
+ const mainScripts = document.documentElement.getAttribute('data-external-script') || '';
+ const childScripts = child?.documentElement.getAttribute('data-external-script') || '';
+ const grandchildScripts = grandchild?.documentElement.getAttribute('data-external-script') || '';
+ const srcdocScripts = srcdoc?.documentElement.getAttribute('data-external-script') || '';
+ const ready = Boolean(
+ document.documentElement.getAttribute('data-inline-script') === 'ran' &&
+ child?.documentElement.getAttribute('data-child-inline-script') === 'ran' &&
+ grandchild?.documentElement.getAttribute('data-grandchild-inline-script') === 'ran' &&
+ srcdoc?.documentElement.getAttribute('data-srcdoc-inline-script') === 'ran' &&
+ mainScripts.includes('/classic.js,') &&
+ mainScripts.includes('/defer.js,') &&
+ mainScripts.includes('/async.js,') &&
+ mainScripts.includes('/module.js,') &&
+ childScripts.includes('/child.js,') &&
+ grandchildScripts.includes('/grandchild.js,') &&
+ srcdocScripts.includes('/srcdoc.js,') &&
+ !document.getElementById('fallback') &&
+ !child?.getElementById('child-fallback') &&
+ !grandchild?.getElementById('grandchild-fallback') &&
+ !srcdoc?.getElementById('srcdoc-fallback')
+ );
+ if (ready) {
+ document.documentElement.setAttribute('data-default-js-probe', 'ready');
+ }
+ return ready;
+})()"#;
+
+const MAIN_PAGE: &str = r#"<!doctype html>
+<html>
+ <head>
+ <link rel="stylesheet" href="/main.css">
+ <noscript><link rel="stylesheet" href="/noscript.css"></noscript>
+ <link rel="preload" as="script" href="/preload.js">
+ <link rel="modulepreload" href="/module-preload.js">
+ <script src="/classic.js"></script>
+ <script defer src="/defer.js"></script>
+ <script async src="/async.js"></script>
+ <script type="importmap">{"imports":{"disabled-alias":"/module.js"}}</script>
+ <script type="module" src="/module.js"></script>
+ <script>document.documentElement.setAttribute("data-inline-script", "ran");</script>
+ </head>
+ <body>
+ <noscript><main id="fallback">main fallback</main></noscript>
+ <div id="styled">imported stylesheet target</div>
+ <iframe id="child" src="/child.html"></iframe>
+ <iframe id="srcdoc-child" srcdoc="<!doctype html><html><head><link rel='stylesheet' href='/srcdoc.css'><noscript><link rel='stylesheet' href='/srcdoc-noscript.css'></noscript><link rel='modulepreload' href='/srcdoc-preload.js'><script src='/srcdoc.js'></script><script>document.documentElement.setAttribute('data-srcdoc-inline-script', 'ran');</script></head><body><noscript><main id='srcdoc-fallback'>srcdoc fallback</main></noscript></body></html>"></iframe>
+ </body>
+</html>"#;
+
+const CHILD_PAGE: &str = r#"<!doctype html>
+<html>
+ <head>
+ <link rel="stylesheet" href="/child.css">
+ <link rel="modulepreload" href="/child-preload.js">
+ <script src="/child.js"></script>
+ <script>document.documentElement.setAttribute("data-child-inline-script", "ran");</script>
+ </head>
+ <body>
+ <noscript><main id="child-fallback">child fallback</main></noscript>
+ <iframe id="grandchild" src="/grandchild.html"></iframe>
+ </body>
+</html>"#;
+
+const GRANDCHILD_PAGE: &str = r#"<!doctype html>
+<html>
+ <head>
+ <link rel="stylesheet" href="/grandchild.css">
+ <link rel="preload" as="script" href="/grandchild-preload.js">
+ <script type="module" src="/grandchild.js"></script>
+ <script>document.documentElement.setAttribute("data-grandchild-inline-script", "ran");</script>
+ </head>
+ <body><noscript><main id="grandchild-fallback">grandchild fallback</main></noscript></body>
+</html>"#;
+
+struct DisableJsFixtureServer {
+ base_url: String,
+ requests: Arc<Mutex<Vec<String>>>,
+ task: JoinHandle<()>,
+}
+
+impl DisableJsFixtureServer {
+ async fn spawn() -> Result<Self> {
+ let requests = Arc::new(Mutex::new(Vec::new()));
+ let listener = TcpListener::bind("127.0.0.1:0").await?;
+ let addr = listener.local_addr()?;
+ let app = Router::new()
+ .route("/page.html", get(|| async { Html(MAIN_PAGE) }))
+ .route("/child.html", get(|| async { Html(CHILD_PAGE) }))
+ .route("/grandchild.html", get(|| async { Html(GRANDCHILD_PAGE) }))
+ .route("/redirect.html", get(redirect_to_page))
+ .route("/meta-refresh.html", get(meta_refresh_page))
+ .route("/document-write.html", get(document_write_page))
+ .fallback(resource)
+ .with_state(Arc::clone(&requests));
+ let task = tokio::spawn(async move {
+ axum::serve(listener, app)
+ .await
+ .expect("disable-js fixture server should serve");
+ });
+ Ok(Self {
+ base_url: format!("http://{addr}"),
+ requests,
+ task,
+ })
+ }
+
+ fn url(&self, path: &str) -> String {
+ format!("{}{path}", self.base_url)
+ }
+
+ fn request_count(&self, path: &str) -> usize {
+ self.requests
+ .lock()
+ .iter()
+ .filter(|request| request.as_str() == path)
+ .count()
+ }
+}
+
+impl Drop for DisableJsFixtureServer {
+ fn drop(&mut self) {
+ self.task.abort();
+ }
+}
+
+async fn redirect_to_page() -> Response {
+ (
+ StatusCode::FOUND,
+ [("location", "/page.html"), ("cache-control", "no-store")],
+ "",
+ )
+ .into_response()
+}
+
+async fn meta_refresh_page() -> Html<&'static str> {
+ Html(
+ r#"<!doctype html>
+<meta http-equiv="refresh" content="0; url=/page.html">
+<script src="/initial.js"></script>
+<script>document.documentElement.setAttribute("data-initial-inline-script", "ran");</script>
+<main id="meta-refresh-source">meta refresh source</main>"#,
+ )
+}
+
+async fn document_write_page() -> Html<&'static str> {
+ Html(r#"<!doctype html><main id="document-write-source">rewrite source</main>"#)
+}
+
+async fn resource(State(requests): State<Arc<Mutex<Vec<String>>>>, uri: Uri) -> Response {
+ let path = uri.path().to_owned();
+ requests.lock().push(path.clone());
+ if path.ends_with(".js") {
+ let body = format!(
+ "(() => {{ const old = document.documentElement.getAttribute('data-external-script') || ''; document.documentElement.setAttribute('data-external-script', old + '{path},'); }})();"
+ );
+ return (
+ StatusCode::OK,
+ [
+ ("content-type", "application/javascript; charset=utf-8"),
+ ("cache-control", "no-store"),
+ ],
+ body,
+ )
+ .into_response();
+ }
+
+ let Some(body) = stylesheet_body(&path) else {
+ return (StatusCode::NOT_FOUND, "not found").into_response();
+ };
+ (
+ StatusCode::OK,
+ [
+ ("content-type", "text/css; charset=utf-8"),
+ ("cache-control", "no-store"),
+ ],
+ body,
+ )
+ .into_response()
+}
+
+fn stylesheet_body(path: &str) -> Option<&'static str> {
+ match path {
+ "/main.css" => Some("@import url('/imported.css'); #fallback { color: rgb(1, 2, 3); }"),
+ "/noscript.css" => Some("#fallback { background-color: rgb(4, 5, 6); }"),
+ "/imported.css" => Some("#styled { color: rgb(7, 8, 9); }"),
+ "/child.css" => Some("#child-fallback { color: rgb(10, 11, 12); }"),
+ "/grandchild.css" => Some("#grandchild-fallback { color: rgb(13, 14, 15); }"),
+ "/srcdoc.css" => Some("#srcdoc-fallback { color: rgb(16, 17, 18); }"),
+ "/srcdoc-noscript.css" => Some("#srcdoc-fallback { background-color: rgb(19, 20, 21); }"),
+ "/document-write.css" => Some("#document-write-fallback { color: rgb(41, 42, 43); }"),
+ _ => None,
+ }
+}
+
+fn fetch_disabled(
+ server: &DisableJsFixtureServer,
+ page_path: &str,
+ extra_args: &[&str],
+) -> Result<Output> {
+ fetch_disabled_until(server, page_path, DISABLED_READY_SCRIPT, extra_args)
+}
+
+fn fetch_disabled_until(
+ server: &DisableJsFixtureServer,
+ page_path: &str,
+ ready_script: &str,
+ extra_args: &[&str],
+) -> Result<Output> {
+ let mut args = vec![
+ "--disable-js",
+ "--with-frames",
+ "--timeout",
+ "5000",
+ "--wait-script",
+ ready_script,
+ ];
+ args.extend_from_slice(extra_args);
+ run_fetch_cli_with_args(&server.url(page_path), &args)
+}
+
+fn assert_disabled_result(
+ output: &Output,
+ server: &DisableJsFixtureServer,
+ scenario: &str,
+) -> String {
+ assert!(
+ output.status.success(),
+ "{scenario} failed: stdout={}\nstderr={}\nrequests={:?}",
+ clean_output(&output.stdout),
+ clean_output(&output.stderr),
+ server.requests.lock().as_slice()
+ );
+ let stdout = clean_output(&output.stdout);
+ assert!(
+ stdout.contains("data-disable-js-probe=\"ready\""),
+ "{scenario} must leave automation expressions available: {stdout}"
+ );
+ for marker in [
+ "data-inline-script=\"ran\"",
+ "data-external-script=\"",
+ "data-child-inline-script=\"ran\"",
+ "data-grandchild-inline-script=\"ran\"",
+ "data-srcdoc-inline-script=\"ran\"",
+ ] {
+ assert!(
+ !stdout.contains(marker),
+ "{scenario} unexpectedly contains executed-script marker {marker}: {stdout}"
+ );
+ }
+ for path in STYLESHEET_PATHS {
+ assert_eq!(
+ server.request_count(path),
+ 1,
+ "{scenario} must fetch required stylesheet {path} exactly once"
+ );
+ }
+ for path in SCRIPT_PATHS {
+ assert_eq!(
+ server.request_count(path),
+ 0,
+ "{scenario} unexpectedly requested script resource {path}"
+ );
+ }
+ stdout
+}
+
+#[test]
+fn keeps_css_noscript_and_nested_frames_without_fetching_scripts() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(DisableJsFixtureServer::spawn())?;
+ let output = fetch_disabled(&server, "/page.html", &[])?;
+ let stdout = assert_disabled_result(&output, &server, "direct HTTP navigation");
+
+ for marker in [
+ "<main id=\"fallback\">main fallback</main>",
+ "child-fallback",
+ "srcdoc-fallback",
+ ] {
+ assert!(
+ stdout.contains(marker),
+ "direct HTTP navigation must serialize fallback marker {marker}: {stdout}"
+ );
+ }
+ assert!(
+ stdout.contains("<script src=\"/classic.js\"></script>"),
+ "disable-js must preserve inert script nodes in the DOM: {stdout}"
+ );
+ Ok(())
+}
+
+#[test]
+fn survives_http_redirect() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(DisableJsFixtureServer::spawn())?;
+ let output = fetch_disabled(&server, "/redirect.html", &[])?;
+ assert_disabled_result(&output, &server, "HTTP redirect navigation");
+ Ok(())
+}
+
+#[test]
+fn survives_meta_refresh_document_replacement() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(DisableJsFixtureServer::spawn())?;
+ let output = fetch_disabled(&server, "/meta-refresh.html", &[])?;
+ let stdout = assert_disabled_result(&output, &server, "meta refresh document replacement");
+ assert!(
+ !stdout.contains("data-initial-inline-script=\"ran\""),
+ "the source Document must not execute before navigation: {stdout}"
+ );
+ Ok(())
+}
+
+#[test]
+fn blocks_dynamic_scripts_and_event_handlers() -> Result<()> {
+ let ready_script = r#"(() => {
+ if (!__BASE_READY__) {
+ return false;
+ }
+ const child = document.getElementById('child').contentDocument;
+ if (!globalThis.__disableJsDynamicProbeStarted) {
+ globalThis.__disableJsDynamicProbeStarted = Date.now();
+ const install = (targetDocument, label, src) => {
+ const inline = targetDocument.createElement('script');
+ inline.textContent = `document.documentElement.setAttribute('data-${label}-dynamic-inline', 'ran')`;
+ targetDocument.body.appendChild(inline);
+
+ const external = targetDocument.createElement('script');
+ external.src = src;
+ targetDocument.body.appendChild(external);
+
+ const button = targetDocument.createElement('button');
+ button.setAttribute(
+ 'onclick',
+ `document.documentElement.setAttribute('data-${label}-event-handler', 'ran')`
+ );
+ targetDocument.body.appendChild(button);
+ button.click();
+ };
+ install(document, 'main', '/dynamic.js');
+ install(child, 'child', '/child-dynamic.js');
+ return false;
+ }
+ const quiet = Date.now() - globalThis.__disableJsDynamicProbeStarted >= 150;
+ const blocked = [document, child].every((targetDocument) =>
+ !targetDocument.documentElement.hasAttribute('data-external-script') &&
+ !targetDocument.documentElement.hasAttribute(
+ targetDocument === document ? 'data-main-dynamic-inline' : 'data-child-dynamic-inline'
+ ) &&
+ !targetDocument.documentElement.hasAttribute(
+ targetDocument === document ? 'data-main-event-handler' : 'data-child-event-handler'
+ )
+ );
+ if (quiet && blocked) {
+ document.documentElement.setAttribute('data-dynamic-disable-js-probe', 'ready');
+ return true;
+ }
+ return false;
+ })()"#
+ .replace("__BASE_READY__", DISABLED_READY_SCRIPT);
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(DisableJsFixtureServer::spawn())?;
+ let output = fetch_disabled_until(&server, "/page.html", &ready_script, &[])?;
+ let stdout = assert_disabled_result(
+ &output,
+ &server,
+ "dynamic scripts and inline event handlers",
+ );
+ assert!(
+ stdout.contains("data-dynamic-disable-js-probe=\"ready\""),
+ "dynamic page-owned code was not observed long enough: {stdout}"
+ );
+ Ok(())
+}
+
+#[test]
+fn fragment_parsers_use_the_disabled_document_policy() -> Result<()> {
+ let ready_script = r#"(() => {
+ if (!__BASE_READY__) {
+ return false;
+ }
+ if (!globalThis.__disableJsFragmentProbeStarted) {
+ globalThis.__disableJsFragmentProbeStarted = true;
+ const child = document.getElementById('child').contentDocument;
+
+ const inner = document.createElement('div');
+ inner.innerHTML = '<noscript><span id="main-inner-fallback"></span></noscript>';
+ document.body.appendChild(inner);
+
+ const unsafe = child.createElement('div');
+ unsafe.setHTMLUnsafe(
+ '<noscript><span id="child-unsafe-fallback"></span></noscript>'
+ );
+ child.body.appendChild(unsafe);
+ }
+
+ const child = document.getElementById('child').contentDocument;
+ const ready = Boolean(
+ document.getElementById('main-inner-fallback') &&
+ child.getElementById('child-unsafe-fallback')
+ );
+ if (ready) {
+ document.documentElement.setAttribute('data-fragment-disable-js-probe', 'ready');
+ }
+ return ready;
+ })()"#
+ .replace("__BASE_READY__", DISABLED_READY_SCRIPT);
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(DisableJsFixtureServer::spawn())?;
+ let output = fetch_disabled_until(&server, "/page.html", &ready_script, &[])?;
+ let stdout = assert_disabled_result(&output, &server, "document-owned fragment parsing");
+
+ assert!(
+ stdout.contains("data-fragment-disable-js-probe=\"ready\""),
+ "fragment parsers did not inherit the disabled Document policy: {stdout}"
+ );
+ Ok(())
+}
+
+#[test]
+fn applies_to_document_open_replacement_parser() -> Result<()> {
+ const READY_SCRIPT: &str = r#"(() => {
+ if (window.name !== '__moli_disable_js_document_write__') {
+ window.name = '__moli_disable_js_document_write__';
+ document.open();
+ document.write(`<!doctype html><html><head>
+ <link rel="stylesheet" href="/document-write.css">
+ <script src="/document-write.js"></script>
+ <script>document.documentElement.setAttribute('data-document-write-inline', 'ran');</script>
+ </head><body><noscript><main id="document-write-fallback">document.write fallback</main></noscript></body></html>`);
+ document.close();
+ return false;
+ }
+ const fallback = document.getElementById('document-write-fallback');
+ const ready = Boolean(
+ fallback &&
+ getComputedStyle(fallback).color === 'rgb(41, 42, 43)' &&
+ !document.documentElement.hasAttribute('data-document-write-inline') &&
+ !document.documentElement.hasAttribute('data-external-script')
+ );
+ if (ready) {
+ document.documentElement.setAttribute('data-document-write-probe', 'ready');
+ }
+ return ready;
+ })()"#;
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(DisableJsFixtureServer::spawn())?;
+ let output = fetch_disabled_until(&server, "/document-write.html", READY_SCRIPT, &[])?;
+
+ assert!(
+ output.status.success(),
+ "script-disabled document.open replacement failed: stdout={}\nstderr={}",
+ clean_output(&output.stdout),
+ clean_output(&output.stderr)
+ );
+ let stdout = clean_output(&output.stdout);
+ assert!(
+ stdout.contains("data-document-write-probe=\"ready\""),
+ "document.open replacement did not preserve the disable-js state: {stdout}"
+ );
+ assert!(
+ stdout.contains("<main id=\"document-write-fallback\">document.write fallback</main>"),
+ "document.open replacement must parse noscript markup: {stdout}"
+ );
+ assert!(!stdout.contains("data-document-write-inline=\"ran\""));
+ assert!(!stdout.contains("data-external-script=\""));
+ assert_eq!(server.request_count("/document-write.css"), 1);
+ assert_eq!(server.request_count("/document-write.js"), 0);
+ Ok(())
+}
+
+#[test]
+fn composes_with_script_stripping() -> Result<()> {
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(DisableJsFixtureServer::spawn())?;
+ let output = fetch_disabled(&server, "/page.html", &["--strip-mode", "js"])?;
+ let stdout = assert_disabled_result(&output, &server, "script-disabled stripped output");
+ assert!(
+ !stdout.contains("<script src=\"/classic.js\"></script>"),
+ "strip-mode=js must remove the inert script node from output: {stdout}"
+ );
+ Ok(())
+}
+
+#[test]
+fn handles_non_streaming_data_document() -> Result<()> {
+ const READY_SCRIPT: &str = r#"(() => {
+ const fallback = document.getElementById('data-fallback');
+ const ready = Boolean(
+ fallback &&
+ getComputedStyle(fallback).color === 'rgb(31, 32, 33)' &&
+ !document.documentElement.hasAttribute('data-data-inline') &&
+ !document.documentElement.hasAttribute('data-data-module')
+ );
+ if (ready) {
+ document.documentElement.setAttribute('data-data-probe', 'ready');
+ }
+ return ready;
+ })()"#;
+ let html = r#"<!doctype html>
+<style>#data-fallback { color: rgb(31, 32, 33); }</style>
+<script>document.documentElement.setAttribute('data-data-inline', 'ran');</script>
+<script type="module">document.documentElement.setAttribute('data-data-module', 'ran');</script>
+<noscript><main id="data-fallback">data fallback</main></noscript>"#;
+ let encoded = url::form_urlencoded::byte_serialize(html.as_bytes())
+ .collect::<String>()
+ .replace('+', "%20");
+ let url = format!("data:text/html,{encoded}");
+ let output = run_fetch_cli_with_args(
+ &url,
+ &[
+ "--disable-js",
+ "--timeout",
+ "5000",
+ "--wait-script",
+ READY_SCRIPT,
+ ],
+ )?;
+
+ assert!(
+ output.status.success(),
+ "script-disabled data URL failed: stdout={}\nstderr={}",
+ clean_output(&output.stdout),
+ clean_output(&output.stderr)
+ );
+ let stdout = clean_output(&output.stdout);
+ assert!(stdout.contains("data-data-probe=\"ready\""), "{stdout}");
+ assert!(
+ stdout.contains("<main id=\"data-fallback\">data fallback</main>"),
+ "data URL noscript fallback was not parsed: {stdout}"
+ );
+ assert!(
+ stdout.contains(
+ "<script>document.documentElement.setAttribute('data-data-inline', 'ran');</script>"
+ ),
+ "data URL script nodes must remain inert DOM content: {stdout}"
+ );
+ assert!(!stdout.contains("data-data-inline=\"ran\""));
+ assert!(!stdout.contains("data-data-module=\"ran\""));
+ Ok(())
+}
+
+#[test]
+fn keeps_script_execution_enabled_by_default() -> Result<()> {
+ const EXECUTED_SCRIPT_PATHS: [&str; 7] = [
+ "/classic.js",
+ "/defer.js",
+ "/async.js",
+ "/module.js",
+ "/child.js",
+ "/grandchild.js",
+ "/srcdoc.js",
+ ];
+ const ACTIVE_STYLESHEET_PATHS: [&str; 5] = [
+ "/main.css",
+ "/imported.css",
+ "/child.css",
+ "/grandchild.css",
+ "/srcdoc.css",
+ ];
+
+ let runtime = tokio::runtime::Runtime::new()?;
+ let server = runtime.block_on(DisableJsFixtureServer::spawn())?;
+ let output = run_fetch_cli_with_args(
+ &server.url("/page.html"),
+ &[
+ "--with-frames",
+ "--timeout",
+ "5000",
+ "--wait-script",
+ ENABLED_READY_SCRIPT,
+ ],
+ )?;
+
+ assert!(
+ output.status.success(),
+ "default script-enabled control failed: stdout={}\nstderr={}",
+ clean_output(&output.stdout),
+ clean_output(&output.stderr)
+ );
+ let stdout = clean_output(&output.stdout);
+ assert!(
+ stdout.contains("data-default-js-probe=\"ready\""),
+ "default behavior must remain script-enabled: {stdout}"
+ );
+ for path in EXECUTED_SCRIPT_PATHS {
+ assert_eq!(
+ server.request_count(path),
+ 1,
+ "default script-enabled control must request {path} exactly once"
+ );
+ }
+ for path in ACTIVE_STYLESHEET_PATHS {
+ assert_eq!(
+ server.request_count(path),
+ 1,
+ "default script-enabled control must request {path} exactly once"
+ );
+ }
+ for path in ["/noscript.css", "/srcdoc-noscript.css"] {
+ assert_eq!(
+ server.request_count(path),
+ 0,
+ "default script-enabled control must keep noscript stylesheet {path} inert"
+ );
+ }
+ Ok(())
+}
diff --git a/skills/moli-webfetch/references/fetch-recipes.md b/skills/moli-webfetch/references/fetch-recipes.md
index f7af4ba5e..7bee6a839 100644
--- a/skills/moli-webfetch/references/fetch-recipes.md
+++ b/skills/moli-webfetch/references/fetch-recipes.md
@@ -82,6 +82,12 @@ moli fetch \
JavaScript runs by default. `--strip-mode js` strips JavaScript from serialized
output; it does not mean that navigation ran without JavaScript.
+Use `--disable-js` when page-authored scripts must neither load nor execute.
+Moli still parses and renders HTML, loads stylesheets (including `@import`),
+loads same-origin frames, and exposes `<noscript>` fallback content. Automation
+predicates such as `--wait-script` remain available; the flag controls page
+code, not the caller's inspection channel.
+
If expected text is absent:
1. Confirm the HTTP status and final URL with `--dump json`.