Skip to content

The headless browser for AI agents and web scraping

Batch Window named-property lookup in native DOM

SGavrl00850f0cf61e
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 761f8b3d..43488792 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -14520,48 +14520,23 @@ function _windowNameEligibleElement(element) {
&& _windowNamedNameTags.has(element.localName);
}
-function _windowNamedSupportedNames(element) {
- const names = [];
- if (!element || element.nodeType !== 1) return names;
- const id = element.getAttribute("id");
- if (id) names.push(id);
- if (_windowNameEligibleElement(element)) {
- const name = element.getAttribute("name");
- if (name && name !== id) names.push(name);
- }
- return names;
-}
-
function _windowNamedCandidates(name) {
const doc = globalThis.document;
if (!doc || !name) return [];
- const elements = doc.querySelectorAll(
- "[id],embed[name],form[name],iframe[name],img[name],object[name]"
- );
- const matches = [];
- for (let i = 0; i < elements.length; i++) {
- const element = elements[i];
- if (element.getAttribute("id") === name
- || (_windowNameEligibleElement(element)
- && element.getAttribute("name") === name)) {
- matches.push(element);
- }
- }
- return matches;
+ return _domParse("window_named_candidates", name) || [];
}
function _windowNamedValue(name) {
const matches = _windowNamedCandidates(name);
if (matches.length === 0) return undefined;
- for (const element of matches) {
- if (element.localName === "iframe" && _windowNameEligibleElement(element)
- && element.getAttribute("name") === name) {
- const window = element.contentWindow;
+ for (const [nid, namedFrame] of matches) {
+ if (namedFrame) {
+ const window = _wrapEl(nid).contentWindow;
if (window) return window;
}
}
- if (matches.length > 1) return HTMLCollection._from(matches);
- return matches[0];
+ if (matches.length > 1) return HTMLCollection._from(matches.map(([nid]) => _wrapEl(nid)));
+ return _wrapEl(matches[0][0]);
}
function _ensureWindowNamedProperty(name) {
@@ -14599,20 +14574,7 @@ function _reconcileWindowNamedProperty(name) {
}
function _windowNamedNamesInTree(root) {
- const names = new Set();
- if (!root) return names;
- if (root.nodeType === 1) {
- for (const name of _windowNamedSupportedNames(root)) names.add(name);
- }
- if (typeof root.querySelectorAll === "function") {
- const elements = root.querySelectorAll(
- "[id],embed[name],form[name],iframe[name],img[name],object[name]"
- );
- for (let i = 0; i < elements.length; i++) {
- for (const name of _windowNamedSupportedNames(elements[i])) names.add(name);
- }
- }
- return names;
+ return new Set(root ? _domParse("window_named_names", root._nid) || [] : []);
}
function _registerWindowNamedTree(root) {
@@ -14629,15 +14591,7 @@ function _reconcileWindowNamedProperties(names) {
if (!names || names.size === 0) return;
const doc = globalThis.document;
if (!doc) return;
- const present = new Set();
- const elements = doc.querySelectorAll(
- "[id],embed[name],form[name],iframe[name],img[name],object[name]"
- );
- for (let i = 0; i < elements.length; i++) {
- for (const name of _windowNamedSupportedNames(elements[i])) {
- if (names.has(name)) present.add(name);
- }
- }
+ const present = _windowNamedNamesInTree(doc);
for (const name of names) {
if (_windowNamedPropertyNames.has(name) && !present.has(name)) {
try { delete globalThis[name]; } catch (_error) {}
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 36a71d3c..7e1d9c7e 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -2079,6 +2079,14 @@ fn op_external_stylesheet_get(state: &OpState, owner_nid: u32, frame_id: u32) ->
serde_json::json!({ "originClean": true, "css": css }).to_string()
}
+fn window_named_attributes(node: &obscura_dom::tree::Node) -> [Option<&str>; 2] {
+ let Some(tag) = node.as_element() else { return [None, None] };
+ let name = (tag.ns.as_ref() == "http://www.w3.org/1999/xhtml"
+ && matches!(tag.local.as_ref(), "embed" | "form" | "iframe" | "img" | "object"))
+ .then(|| node.get_attribute_ns("", "name")).flatten();
+ [node.get_attribute_ns("", "id"), name].map(|value| value.filter(|value| !value.is_empty()))
+}
+
#[op2]
#[string]
fn op_dom(
@@ -2372,6 +2380,34 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->
});
"null".to_string()
}
+ "window_named_names" => {
+ let root = NodeId::new(arg1.parse().unwrap_or(u32::MAX));
+ let mut names = Vec::new();
+ let mut seen = HashSet::new();
+ for node in std::iter::once(root).chain(dom.descendants(root)) {
+ dom.with_node(node, |node| {
+ for name in window_named_attributes(node).into_iter().flatten() {
+ if seen.insert(name.to_string()) { names.push(name.to_string()); }
+ }
+ });
+ }
+ serde_json::to_string(&names).unwrap_or_else(|_| "[]".into())
+ }
+ "window_named_candidates" => {
+ if arg1.is_empty() { return "[]".into(); }
+ let mut matches = Vec::new();
+ for node_id in dom.descendants(dom.document()) {
+ dom.with_node(node_id, |node| {
+ let names = window_named_attributes(node);
+ if names.contains(&Some(arg1.as_str())) {
+ let named_frame = names[1] == Some(arg1.as_str())
+ && node.as_element().is_some_and(|tag| tag.local.as_ref() == "iframe");
+ matches.push((node_id.index(), named_frame));
+ }
+ });
+ }
+ serde_json::to_string(&matches).unwrap_or_else(|_| "[]".into())
+ }
"document_node_id" => dom.document().index().to_string(),
"document_compat_mode" => if dom.is_quirks() { "BackCompat" } else { "CSS1Compat" }.into(),
"document_title" => {
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 1c392ef0..e0dd5ef4 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -9108,6 +9108,37 @@ mod tests {
);
}
+ #[test]
+ fn window_named_access_uses_native_attributes_not_page_overrides() {
+ let mut rt = setup_runtime("<html><body><div id='nativeName'></div></body></html>");
+ let result = rt.evaluate(r#"
+ const element = document.getElementById('nativeName');
+ let calls = 0;
+ element.getAttribute = () => { calls++; return null; };
+ const documentQuery = document.querySelectorAll;
+ document.querySelectorAll = function(selector) {
+ if (selector.includes('[id]')) { calls++; return []; }
+ return documentQuery.call(this,selector);
+ };
+ const existing = window.nativeName === element;
+ const subtree = document.createElement('section');
+ subtree.innerHTML = '<span id="insertedName"></span><img name="insertedImage">';
+ const span = subtree.firstElementChild;
+ const image = subtree.lastElementChild;
+ const elementQuery = subtree.querySelectorAll;
+ subtree.querySelectorAll = function(selector) {
+ if (selector.includes('[id]')) { calls++; return []; }
+ return elementQuery.call(this,selector);
+ };
+ span.getAttribute = image.getAttribute = () => { calls++; return null; };
+ document.body.appendChild(subtree);
+ const inserted = window.insertedName === span && window.insertedImage === image;
+ subtree.remove();
+ return [existing, inserted, 'insertedName' in window, 'insertedImage' in window, calls];
+ "#).unwrap();
+ assert_eq!(result, serde_json::json!([true,true,false,false,0]));
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn inserting_a_frame_before_itself_retires_its_old_document_without_reordering() {
let mut rt = setup_runtime("<html><body><b id='before'></b><iframe id='frame'></iframe><b id='after'></b></body></html>");