fix(html): preserve document scripting mode

This commit is contained in:
ldm0
2026-11-24 14:28:13 +08:00
parent 6914c12a1a
commit 732d81900e
12 changed files with 300 additions and 32 deletions
+19 -4
View File
@@ -72,6 +72,8 @@ struct DocumentMetadata {
kind: DocumentKind,
interface: DocumentInterface,
design_mode_enabled: bool,
// Portable parser policy; inert/template documents keep scripting disabled.
scripting_enabled: bool,
default_language: Option<Box<str>>,
source_last_modified_ms: Option<f64>,
base_url_state: DocumentBaseUrlState,
@@ -97,14 +99,18 @@ impl Document {
}
pub fn new_html(url: Url) -> Self {
Self::new_with_kind(url, DocumentKind::Html)
Self::new_html_with_scripting(url, true)
}
pub fn new_html_with_scripting(url: Url, scripting_enabled: bool) -> Self {
Self::new_with_kind(url, DocumentKind::Html, scripting_enabled)
}
pub fn new_xml(url: Url) -> Self {
Self::new_with_kind(url, DocumentKind::Xml)
Self::new_with_kind(url, DocumentKind::Xml, true)
}
fn new_with_kind(url: Url, kind: DocumentKind) -> Self {
fn new_with_kind(url: Url, kind: DocumentKind, scripting_enabled: bool) -> Self {
let (content_type, interface) = match kind {
DocumentKind::Html => ("text/html", DocumentInterface::Html),
DocumentKind::Xml => ("application/xml", DocumentInterface::Xml),
@@ -120,6 +126,7 @@ impl Document {
kind,
interface,
design_mode_enabled: false,
scripting_enabled,
default_language: None,
source_last_modified_ms: None,
meta_referrer_policy: None,
@@ -130,7 +137,7 @@ impl Document {
pub(super) fn new_inert_template(kind: DocumentKind) -> Self {
let url = Url::parse("about:blank").expect("about:blank is valid");
let mut document = Self::new_with_kind(url, kind);
let mut document = Self::new_with_kind(url, kind, false);
document.metadata.interface = DocumentInterface::Document;
document.arena_state.is_inert_template_document = true;
document
@@ -258,6 +265,10 @@ impl Document {
self.metadata.design_mode_enabled
}
pub fn scripting_enabled(&self) -> bool {
self.metadata.scripting_enabled
}
pub fn fallback_base_url(&self) -> &Url {
self.metadata.base_url_state.fallback_base_url()
}
@@ -297,6 +308,10 @@ impl Document {
self.metadata.design_mode_enabled = design_mode_enabled;
}
pub fn set_scripting_enabled(&mut self, scripting_enabled: bool) {
self.metadata.scripting_enabled = scripting_enabled;
}
pub fn set_css_target(&mut self, target: Option<NativeNodeId>) -> bool {
if self.arena_state.css_target == target {
return false;
+40 -1
View File
@@ -22,8 +22,19 @@ impl DomHost {
}
pub fn create_detached_html_document_with_url(&mut self, url: Url) -> DomHandle {
self.create_detached_html_document_with_url_and_scripting(url, true)
}
pub fn create_detached_html_document_with_url_and_scripting(
&mut self,
url: Url,
scripting_enabled: bool,
) -> DomHandle {
self.dom.create_node(
NodeData::Document(Box::new(Document::new_html(url))),
NodeData::Document(Box::new(Document::new_html_with_scripting(
url,
scripting_enabled,
))),
None,
false,
false,
@@ -1075,6 +1086,15 @@ impl DomHost {
true
}
pub fn document_scripting_enabled_for_handle(
&self,
document_handle: DomHandle,
) -> Option<bool> {
self.node(document_handle)
.and_then(Node::as_document)
.map(Document::scripting_enabled)
}
pub fn document_base_url(&self) -> Option<Url> {
self.document_base_url_for_handle(self.document_handle())
}
@@ -1266,6 +1286,25 @@ impl DomHost {
true
}
pub fn set_document_scripting_enabled_for_handle(
&mut self,
document_handle: DomHandle,
scripting_enabled: bool,
) -> bool {
let Some(document) = self
.node_mut(document_handle)
.and_then(|node| node.data_mut().as_document_mut())
else {
return false;
};
if document.scripting_enabled() == scripting_enabled {
return false;
}
document.set_scripting_enabled(scripting_enabled);
self.record_mutation(MutationScope::LocalState);
true
}
pub fn set_document_quirks_mode_for_handle(
&mut self,
document_handle: DomHandle,
@@ -995,6 +995,24 @@ pub(super) fn serialize_html(
.then_some(html)
}
pub(super) fn serialize_html_with_stored_scripting_state(
dom: &NativeDom,
node_id: NativeNodeId,
target: HtmlSerializationTarget,
) -> Option<String> {
let scripting_enabled_for_node =
|node| dom.node_document_scripting_enabled(node).unwrap_or(false);
let mut html = String::new();
serialize_html_into_sink(
dom,
node_id,
HtmlSerializationOptions::new(target, &scripting_enabled_for_node),
&mut html,
)
.expect("standard node serialization cannot enter embedded documents")
.then_some(html)
}
pub(in crate::native) fn serialize_html_with_options<'a>(
dom: &'a NativeDom,
node_id: NativeNodeId,
@@ -1026,7 +1044,8 @@ pub(super) fn serialize_html_with_limit(
node_id: NativeNodeId,
max_bytes: usize,
) -> Result<Option<String>, HtmlSerializationLimitExceeded> {
let scripting_enabled_for_node = |_: NativeNodeId| true;
let scripting_enabled_for_node =
|node| dom.node_document_scripting_enabled(node).unwrap_or(false);
let mut out = BoundedHtmlSerialization::new(max_bytes);
if !serialize_html_into_sink(
dom,
+19 -4
View File
@@ -12,7 +12,9 @@ pub(super) use engine::{
HtmlSerializationOptions, HtmlSerializationTarget, HtmlSerializedShadowRoot,
HtmlShadowRootProvider, serialize_html_with_options,
};
use engine::{serialize_html, serialize_html_with_limit};
use engine::{
serialize_html, serialize_html_with_limit, serialize_html_with_stored_scripting_state,
};
use std::borrow::Cow;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -153,7 +155,12 @@ impl NativeDom {
}
pub fn serialize_document(&self) -> String {
self.serialize_document_with_scripting_enabled(true)
serialize_html_with_stored_scripting_state(
self,
self.document_node_id,
HtmlSerializationTarget::ChildrenOnly,
)
.unwrap_or_default()
}
pub fn serialize_document_with_scripting_enabled(&self, scripting_enabled: bool) -> String {
@@ -167,7 +174,11 @@ impl NativeDom {
}
pub fn outer_html(&self, node_id: NativeNodeId) -> Option<String> {
self.outer_html_with_scripting_enabled(node_id, true)
serialize_html_with_stored_scripting_state(
self,
node_id,
HtmlSerializationTarget::IncludeNode,
)
}
pub fn outer_html_with_scripting_enabled(
@@ -197,7 +208,11 @@ impl NativeDom {
}
pub fn inner_html(&self, node_id: NativeNodeId) -> Option<String> {
self.inner_html_with_scripting_enabled(node_id, true)
serialize_html_with_stored_scripting_state(
self,
node_id,
HtmlSerializationTarget::ChildrenOnly,
)
}
pub fn inner_html_with_scripting_enabled(
+14 -1
View File
@@ -188,13 +188,20 @@ impl NativeDom {
}
pub fn new_html(final_url: url::Url) -> Self {
Self::new_html_with_scripting(final_url, true)
}
pub fn new_html_with_scripting(final_url: url::Url, scripting_enabled: bool) -> Self {
let document_node_id = NativeNodeId::new(0);
let document_node = Node::new(
document_node_id,
None,
None,
NodeFlags::new(true),
NodeData::Document(Box::new(Document::new_html(final_url))),
NodeData::Document(Box::new(Document::new_html_with_scripting(
final_url,
scripting_enabled,
))),
);
Self {
nodes: NativeNodeStorage::from_node(document_node),
@@ -2864,6 +2871,12 @@ mod tests {
.and_then(Node::owner_document)
.expect("template content owner document");
assert_ne!(content_owner, dom.document_node_id());
assert_eq!(
dom.node(content_owner)
.and_then(Node::as_document)
.map(Document::scripting_enabled),
Some(false)
);
let child = dom.create_element("span");
assert_eq!(
+11
View File
@@ -326,6 +326,17 @@ impl NativeDom {
})
}
pub fn node_document_scripting_enabled(&self, node_id: NativeNodeId) -> Option<bool> {
let node = self.node(node_id)?;
if let Some(document) = node.as_document() {
return Some(document.scripting_enabled());
}
let owner_document = node.owner_document()?;
self.node(owner_document)
.and_then(Node::as_document)
.map(|document| document.scripting_enabled())
}
fn collect_matching_elements(
&self,
root: NativeNodeId,
+41 -8
View File
@@ -444,7 +444,13 @@ impl HtmlParser {
}
pub fn parse_dom_host(&self, final_url: Url, html: String) -> DomHost {
let stream = self.start_document(final_url);
let target =
ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots_and_scripting(
final_url,
true,
self.scripting_enabled,
);
let stream = HtmlTreeSinkStream::from_target_with_scripting(target, self.scripting_enabled);
for chunk in html_chunks(&html) {
stream.feed(chunk);
}
@@ -457,7 +463,11 @@ impl HtmlParser {
html: String,
) -> NativeDom {
let target =
ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots(final_url, false);
ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots_and_scripting(
final_url,
false,
self.scripting_enabled,
);
let stream = HtmlTreeSinkStream::from_target_with_scripting(target, self.scripting_enabled);
for chunk in html_chunks(&html) {
stream.feed(chunk);
@@ -472,8 +482,10 @@ impl HtmlParser {
/// Start a text document using the HTML tokenizer's plaintext state.
/// Subsequent chunks remain literal text inside the browser-owned `pre`.
pub fn start_text_document(&self, final_url: Url, content_type: &str) -> DocumentStream {
let stream =
DocumentStream::new_text_document(new_parser_stream_html_tree_sink_target(final_url));
let stream = DocumentStream::new_text_document(new_parser_stream_html_tree_sink_target(
final_url,
self.scripting_enabled,
));
stream.inner.initialize_text_document();
let mut host = stream.inner.take_parser_stream_dom_host();
let document_handle = host.document_handle();
@@ -544,10 +556,12 @@ impl HtmlParser {
allow_declarative_shadow_roots: bool,
scripting_enabled: bool,
) -> NativeDom {
let target = ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots(
final_url,
allow_declarative_shadow_roots,
);
let target =
ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots_and_scripting(
final_url,
allow_declarative_shadow_roots,
scripting_enabled,
);
let context = HtmlFragmentContext::new(None, context_namespace, context_local_name);
let sink = DocumentSink::new(target);
let parser = HtmlParserSession::new_fragment(
@@ -2267,6 +2281,25 @@ mod tests {
);
}
#[test]
fn standalone_html_parser_preserves_the_requested_scripting_mode() {
let document = HtmlParser::SCRIPTING_DISABLED.parse_without_declarative_shadow_roots(
Url::parse("https://example.test/").expect("test url"),
"<body><noscript>&amp;&nbsp;&lt;&gt;</noscript></body>".to_owned(),
);
assert_eq!(
document
.document()
.map(|document| document.scripting_enabled()),
Some(false)
);
let noscript = first_element_by_ns(&document, HTML_NS, "noscript");
assert_eq!(
document.inner_html(noscript).as_deref(),
Some("&amp;&nbsp;&lt;&gt;")
);
}
#[test]
fn mathml_annotation_xml_text_html_is_html_integration_point() {
let document = parse_test_document(concat!(
+61 -8
View File
@@ -2156,15 +2156,15 @@ impl ParserStreamHtmlTreeSinkTarget {
Some(move || sink.finish())
}
fn new(final_url: Url) -> Self {
Self::new_with_declarative_shadow_roots(final_url, true)
}
pub(super) fn new_with_declarative_shadow_roots(
pub(super) fn new_with_declarative_shadow_roots_and_scripting(
final_url: Url,
allow_declarative_shadow_roots: bool,
scripting_enabled: bool,
) -> Self {
let dom_host = DomHost::from_dom(NativeDom::new(final_url.clone()));
let dom_host = DomHost::from_dom(NativeDom::new_html_with_scripting(
final_url.clone(),
scripting_enabled,
));
let document_handle = dom_host.document_handle();
Self {
owned_dom_host: Some(dom_host),
@@ -3744,8 +3744,13 @@ impl ParserStreamHtmlTreeSinkTarget {
pub(super) fn new_parser_stream_html_tree_sink_target(
final_url: Url,
scripting_enabled: bool,
) -> ParserStreamHtmlTreeSinkTarget {
ParserStreamHtmlTreeSinkTarget::new(final_url)
ParserStreamHtmlTreeSinkTarget::new_with_declarative_shadow_roots_and_scripting(
final_url,
true,
scripting_enabled,
)
}
pub(super) fn new_parser_stream_html_tree_sink_stream(
@@ -3753,7 +3758,7 @@ pub(super) fn new_parser_stream_html_tree_sink_stream(
scripting_enabled: bool,
) -> HtmlTreeSinkStream {
HtmlTreeSinkStream::from_target_with_scripting(
new_parser_stream_html_tree_sink_target(final_url),
new_parser_stream_html_tree_sink_target(final_url, scripting_enabled),
scripting_enabled,
)
}
@@ -4514,6 +4519,54 @@ fn parser_stream_live_fragment_root_writes_fragment() {
);
}
#[test]
fn live_fragment_parser_preserves_noscript_when_scripting_is_disabled() {
let url = Url::parse("https://example.test/").expect("test url");
let mut dom_host = DomHost::from_dom(NativeDom::new_html_with_scripting(url.clone(), false));
let document = dom_host.document_handle();
let html = dom_host.create_element("html");
let body = dom_host.create_element("body");
assert!(dom_host.append_child(document, html));
assert!(dom_host.append_child(html, body));
let existing_noscript = dom_host.create_element("noscript");
let existing_text = dom_host.create_text_node("<em>existing&</em>");
assert!(dom_host.append_child(existing_noscript, existing_text));
assert!(dom_host.append_child(body, existing_noscript));
let fragment = dom_host.create_document_fragment_for_document(document);
let ptr = &mut dom_host as *mut DomHost;
let mut effects = DomMutationEffects::default();
{
let mut collector = TestMutationEffectCollector {
host: ptr,
effects: &mut effects,
panic_on_mutation: false,
finish_texts: None,
};
crate::HtmlParser::with_scripting_enabled(false).parse_fragment_into_live_dom(
url,
fragment,
document,
HtmlFragmentContext::new(Some(body), "http://www.w3.org/1999/xhtml", "body"),
"<noscript>&lt;em&gt;fallback&amp;&lt;/em&gt;</noscript><span>tail</span>",
&mut collector,
false,
);
}
assert_eq!(
dom_host
.elements_by_tag_name(fragment, "noscript", false)
.len(),
1,
"a scripting-disabled live fragment must preserve its noscript root"
);
assert_eq!(
dom_host.elements_by_tag_name(fragment, "span", false).len(),
1
);
}
#[test]
fn live_fragment_parser_uses_template_contents_owner_document() {
let url = Url::parse("https://example.test/").expect("test url");
@@ -549,8 +549,13 @@ impl DocumentRuntime {
self.dom_host.create_detached_xml_document()
}
pub(crate) fn create_detached_html_document_with_url(&mut self, url: url::Url) -> DomHandle {
self.dom_host.create_detached_html_document_with_url(url)
pub(crate) fn create_detached_html_document_with_url_and_scripting(
&mut self,
url: url::Url,
scripting_enabled: bool,
) -> DomHandle {
self.dom_host
.create_detached_html_document_with_url_and_scripting(url, scripting_enabled)
}
pub(crate) fn create_detached_xml_document_with_url(&mut self, url: url::Url) -> DomHandle {
@@ -822,6 +822,10 @@ impl PageScriptHost {
}
self.child_browsing_context_host_for_document_handle(document_handle)
.map(|handle| self.child_browsing_context_scripting_enabled(handle))
.or_else(|| {
self.dom_host()
.document_scripting_enabled_for_handle(document_handle)
})
// DOMParser and document.implementation documents have no browsing
// context, so scripting is disabled for their fragment parsers too.
.unwrap_or(false)
@@ -58,16 +58,20 @@ fn create_native_detached_document_handle_with_url(
scope: &mut v8::PinScope<'_, '_>,
kind: &str,
url: Url,
scripting_enabled: bool,
) -> Option<DomHandle> {
let runtime_ptr = context_host_ptr_from_global_bridge(scope)?;
let runtime = unsafe { &mut *runtime_ptr };
let source = runtime.current_realm_document_execution_context(scope);
let handle = if kind == "html" {
runtime.create_detached_html_document_with_url(url)
runtime.create_detached_html_document_with_url_and_scripting(url, scripting_enabled)
} else {
runtime.create_detached_xml_document_with_url(url)
};
runtime.set_inert_document_execution_context(handle, source);
let _ = runtime
.dom_host_mut()
.set_document_scripting_enabled_for_handle(handle, scripting_enabled);
Some(handle)
}
@@ -84,6 +88,7 @@ fn new_detached_document_shell<'s>(
kind: &str,
content_type: &str,
url: Url,
scripting_enabled: bool,
) -> Option<v8::Local<'s, v8::Object>> {
let to_string_tag = if kind == "html" {
Some("HTMLDocument")
@@ -105,7 +110,8 @@ fn new_detached_document_shell<'s>(
v8_string(scope, "complete")?.into(),
);
define_detached_state(scope, document, state);
let handle = create_native_detached_document_handle_with_url(scope, kind, url)?;
let handle =
create_native_detached_document_handle_with_url(scope, kind, url, scripting_enabled)?;
define_detached_native_handle(scope, document, handle);
set_detached_document_content_type(scope, document, content_type)?;
install_detached_document_instance_properties(scope, document, kind);
@@ -189,6 +195,7 @@ pub(crate) fn build_detached_document_object_from_dom_host_with_content_type<'s>
) -> Option<v8::Local<'s, v8::Object>> {
let url = detached_document_url(&parsed);
let quirks_mode = parsed.dom().document()?.quirks_mode();
let scripting_enabled = parsed.dom().document()?.scripting_enabled();
let compat_mode = if quirks_mode == selectors::matching::QuirksMode::Quirks {
"BackCompat"
} else {
@@ -196,7 +203,7 @@ pub(crate) fn build_detached_document_object_from_dom_host_with_content_type<'s>
};
let content_type = content_type.unwrap_or(parsed.dom().document()?.content_type());
let character_set = character_set.unwrap_or(parsed.dom().document()?.character_set());
let document = new_detached_document_shell(scope, kind, content_type, url)?;
let document = new_detached_document_shell(scope, kind, content_type, url, scripting_enabled)?;
if let Some(state) = detached_state_object(scope, document) {
let _ = state.set(
scope,
@@ -306,6 +313,7 @@ pub(in crate::native_bridge::document) fn build_detached_html_document_object<'s
"html",
"text/html",
Url::parse("about:blank").expect("static about:blank parses"),
false,
)?;
populate_native_html_document_shell(scope, document, title)?;
Some(document)
@@ -331,6 +339,7 @@ pub(in crate::native_bridge::document) fn build_detached_document_object<'s>(
kind,
content_type,
Url::parse("about:blank").expect("static about:blank parses"),
false,
)?;
if let Some(doctype) = doctype {
let doctype = if detached_is_node(scope, doctype) {
@@ -1775,3 +1775,55 @@ fn domparser_xml_preserves_requested_content_type_for_success_and_error_document
r#"[["text/xml","text/xml","html"],["application/xml","application/xml","html"],["application/xhtml+xml","application/xhtml+xml","html"],["image/svg+xml","image/svg+xml","html"]]"#
);
}
#[test]
fn offline_html_documents_parse_and_serialize_noscript_with_scripting_disabled() {
let mut vm = new_storage_test_vm("https://offline-noscript.test/");
let result = vm
.eval(
r#"
(() => {
const encoded = '&amp;&nbsp;&lt;&gt;';
const decoded = '&\u00a0<>';
const markup = value => `<noscript>${value}</noscript>`;
const matches = (node, serialization) =>
node.textContent === decoded && node.innerHTML === serialization;
const live = document.createElement('div');
live.innerHTML = markup(decoded);
const parsed = new DOMParser().parseFromString(
`<body>${markup(encoded)}</body>`,
'text/html'
);
const template = document.createElement('template');
template.innerHTML = markup(encoded);
const created = document.implementation.createHTMLDocument('');
created.body.innerHTML = `<pre>${markup(encoded)}</pre>`;
const contextualDocument = document.implementation.createHTMLDocument('');
const range = contextualDocument.createRange();
range.selectNode(contextualDocument.body);
const contextual = range.createContextualFragment(markup(encoded));
const written = document.implementation.createHTMLDocument('');
written.write(`<div>${markup(decoded)}</div>`);
return [
matches(live.firstChild, decoded),
matches(parsed.body.firstChild, encoded),
matches(template.content.firstChild, encoded),
matches(created.body.firstChild.firstChild, encoded),
matches(contextual.firstChild, encoded),
matches(written.body.firstChild.firstChild, encoded)
].join('|');
})()
"#,
)
.expect("offline noscript parsing and serialization probe should evaluate");
assert_eq!(result, "true|true|true|true|true|true");
}