Skip to content

The headless browser for AI agents and web scraping

fix(js): mirror foster-parented written nodes at live anchors

SGavrlee7497388c7a
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 8b0a694b..681038d6 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -6387,7 +6387,13 @@ function _insertWrittenNodes(doc, placements) {
if (!node) continue;
if (node.nodeType === 10) doc._doctype = undefined;
if (node.nodeType === 1 && node.tagName === 'SCRIPT') __documentWriteScripts.add(node);
- if (parentNid >= 0) {
+ var beforeNid = +placements[i][2];
+ var before = beforeNid >= 0 ? _wrap(beforeNid) : null;
+ // A script can move or remove the parser's insertion anchor between writes.
+ // Use its live parent when present, or append at the normal insertion point.
+ if (before && before.parentNode) {
+ before.parentNode.insertBefore(node, before);
+ } else if (parentNid >= 0) {
var parent = _wrap(parentNid);
if (parent) parent.appendChild(node);
} else if (after) {
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 4adc3dab..0b0a853b 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -2472,7 +2472,7 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->
// document.write() feeds the document's input stream, so the calls
// share one parser and one tokenizer state. Returns the nodes that
// became complete with this call, for the caller to run scripts among.
- // Returns [[parent, node], …], parents before children. A `parent` of -1 means the node
+ // Returns [[parent, node, before], …], parents before children. A `parent` of -1 means the node
// belongs at the insertion point, which the caller knows. Nothing is inserted here:
// that must go through Node.appendChild on the JS side, because that call also reports
// the mutation, registers window named access, and loads a written stylesheet.
@@ -2495,12 +2495,13 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->
{
gs.document_write_inserted_script.set(true);
}
- let pairs: Vec<[i32; 2]> = placements
+ let pairs: Vec<[i32; 3]> = placements
.iter()
.map(|placement| {
[
placement.parent.map_or(-1, |id| id.index() as i32),
placement.node.index() as i32,
+ placement.before.map_or(-1, |id| id.index() as i32),
]
})
.collect();
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index be4fe1d9..4d316c00 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -23121,6 +23121,104 @@ mod tests {
);
}
+ #[test]
+ fn document_write_foster_parenting_preserves_order_and_mutation_records() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt.evaluate(r#"
+ var scriptTestSetup = true;
+ document.open();
+ document.write('<table id="table"><tr><td>cell');
+ const table = document.getElementById('table');
+ const label = node => node.nodeType === 3 ? node.data : node.nodeName;
+ const observer = new MutationObserver(() => {});
+ observer.observe(document.body, {childList: true});
+ document.write('</td></tr>outside<b>bold</b>tail</table><p>end</p>');
+ const added = observer.takeRecords().flatMap(record => Array.from(record.addedNodes, label));
+ observer.disconnect();
+ const order = Array.from(document.body.childNodes, label);
+ document.close();
+ return {order, added, sameTable: document.getElementById('table') === table};
+ "#).unwrap();
+ assert_eq!(result, serde_json::json!({
+ "order": ["outside", "B", "tail", "TABLE", "P"],
+ "added": ["outside", "B", "tail", "P"],
+ "sameTable": true,
+ }));
+ }
+
+ #[test]
+ fn document_write_foster_parenting_grows_the_existing_text_node() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt.evaluate(r#"
+ var scriptTestSetup = true;
+ document.open();
+ document.write('<table id="table"><tr><td>cell');
+ const table = document.getElementById('table');
+ document.write('</td></tr>outside<!--flush-->');
+ const text = document.body.firstChild;
+ const first = text.nodeType === 3 ? text.data : null;
+ document.write('more</table>');
+ const second = document.body.firstChild.nodeType === 3 ? document.body.firstChild.data : null;
+ const sameText = document.body.firstChild === text;
+ document.close();
+ return {first, second, sameText, sameTable: document.getElementById('table') === table};
+ "#).unwrap();
+ assert_eq!(result, serde_json::json!({
+ "first": "outside", "second": "outsidemore", "sameText": true, "sameTable": true,
+ }));
+ }
+
+ #[test]
+ fn document_write_foster_parenting_uses_the_live_anchor_parent() {
+ for moved in [false, true] {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ rt.evaluate(&format!("globalThis.moveWrittenTable = {moved}")).unwrap();
+ let result = rt.evaluate(r#"
+ var scriptTestSetup = true;
+ document.open();
+ document.write('<table id="table"><tr><td>cell');
+ const table = document.getElementById('table');
+ let parent = document.body;
+ if (moveWrittenTable) {
+ parent = document.createElement('div');
+ document.body.appendChild(parent);
+ parent.appendChild(table);
+ } else {
+ table.remove();
+ }
+ const observer = new MutationObserver(() => {});
+ observer.observe(parent, {childList: true});
+ let error = null;
+ try { document.write('</td></tr>outside</table>'); }
+ catch (caught) { error = caught.name; }
+ const label = node => node.nodeType === 3 ? node.data : node.nodeName;
+ const added = observer.takeRecords().flatMap(record => Array.from(record.addedNodes, label));
+ observer.disconnect();
+ const order = Array.from(parent.childNodes, label);
+ document.close();
+ return {order, added, error, sameTable: moveWrittenTable ? parent.lastChild === table : table.parentNode === null};
+ "#).unwrap();
+ let order = if moved { vec!["outside", "TABLE"] } else { vec!["outside"] };
+ assert_eq!(result, serde_json::json!({
+ "order": order, "added": ["outside"], "error": null, "sameTable": true,
+ }));
+ }
+ }
+
+ #[test]
+ fn document_write_foster_parenting_keeps_the_inline_insertion_point() {
+ let mut rt = setup_runtime("<html><body><script id=writer></script></body></html>");
+ let result = rt.evaluate(r#"
+ var scriptTestSetup = true;
+ globalThis.__currentScriptNid = document.getElementById('writer')._nid;
+ document.write('<table id="table"><tr><td>cell');
+ document.write('</td></tr>outside</table><p>end</p>');
+ globalThis.__currentScriptNid = 0;
+ return Array.from(document.body.childNodes, node => node.nodeType === 3 ? node.data : node.nodeName);
+ "#).unwrap();
+ assert_eq!(result, serde_json::json!(["SCRIPT", "outside", "TABLE", "P"]));
+ }
+
// WebIDL puts interface operations on the interface prototype with
// enumerable: true, so in a browser Object.keys(MutationObserver.prototype)
// is ['observe', 'disconnect', 'takeRecords']. ES class methods are
diff --git a/crates/obscura-js/src/write_stream.rs b/crates/obscura-js/src/write_stream.rs
index 31280970..1b995f9e 100644
--- a/crates/obscura-js/src/write_stream.rs
+++ b/crates/obscura-js/src/write_stream.rs
@@ -38,6 +38,7 @@ impl Tracer for RetainedNodes {
pub(crate) struct Placement {
pub(crate) parent: Option<NodeId>,
pub(crate) node: NodeId,
+ pub(crate) before: Option<NodeId>,
}
/// A `<script>` runs as soon as it is inserted, so a half-written one must not.
@@ -106,27 +107,43 @@ impl DocumentWriteStream {
// Only look at what is new. A walk over all children would cost as much per call as
// the input stream written so far is long, so quadratic over a thousand calls. Measured at
// 5000 calls: 852 ms versus 4130 ms.
- let mut stack: Vec<NodeId> = fresh_children(source, root, handed_over);
+ let mut stack: Vec<(NodeId, Option<NodeId>)> = fresh_children(source, root, handed_over)
+ .into_iter().map(|id| (id, None)).collect();
- while let Some(current) = stack.pop() {
+ while let Some((current, before)) = stack.pop() {
let node = match source.get_node(current) {
Some(node) => node,
None => continue,
};
if let Some(&copy) = handed_over.get(&current) {
+ // Foster parenting inserts before an existing sibling. Carry that sibling
+ // as a stable anchor, and stop at the first already-copied predecessor.
+ let mut previous = node.prev_sibling;
+ while let Some(id) = previous {
+ let Some(sibling) = source.get_node(id) else { break; };
+ if handed_over.contains_key(&id) {
+ if sibling.is_text() { stack.push((id, None)); }
+ break;
+ }
+ stack.push((id, Some(copy)));
+ previous = sibling.prev_sibling;
+ }
// A text node at the end of the input stream grows with every call and stays the
- // same node. Elements no longer change after their creation.
+ // same node, including immediately before a foster-parenting anchor.
if node.is_text() {
let text = source.text_content(current);
- dom.with_node_mut(copy, |n| {
- if let NodeData::Text { contents } = &mut n.data {
- *contents = text;
- }
- });
+ if dom.with_node(copy, |n| matches!(&n.data,
+ NodeData::Text { contents } if contents == &text)) != Some(true) {
+ dom.with_node_mut(copy, |n| {
+ if let NodeData::Text { contents } = &mut n.data {
+ *contents = text;
+ }
+ });
+ }
}
for child in fresh_children(source, current, handed_over) {
- stack.push(child);
+ stack.push((child, None));
}
continue;
}
@@ -151,7 +168,7 @@ impl DocumentWriteStream {
};
dom.detach(copy);
map_subtree(source, current, dom, copy, handed_over);
- placements.push(Placement { parent, node: copy });
+ placements.push(Placement { parent, node: copy, before });
continue;
}
@@ -159,9 +176,9 @@ impl DocumentWriteStream {
// never closed appear at once instead of never.
let copy = dom.new_node(node.data.clone());
handed_over.insert(current, copy);
- placements.push(Placement { parent, node: copy });
+ placements.push(Placement { parent, node: copy, before });
for child in fresh_children(source, current, handed_over) {
- stack.push(child);
+ stack.push((child, None));
}
}
@@ -172,9 +189,9 @@ impl DocumentWriteStream {
/// The children of `parent` still to do, as a stack: the top element is processed first.
///
/// The walk goes backward from the last child and stops at the first one already handed over.
-/// The parser only appends at the back, so everything before it is done. This one already
-/// handed-over child comes back along, because a text node at the end of the input stream keeps
-/// growing and an open element still receives children.
+/// This already handed-over child comes back along, because a text node keeps growing, an
+/// open element receives children, and foster parenting can add preceding siblings. The mirror
+/// discovers those siblings at this boundary rather than rescanning all earlier children.
fn fresh_children(
source: &DomTree,
parent: NodeId,