Skip to content

The headless browser for AI agents and web scraping

Expose named elements and SVG path interfaces

SGavrl9d2164078d12
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 67ed9772..03cef9ca 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -53,6 +53,8 @@
'MessageChannel', 'MessagePort', 'BroadcastChannel', 'CustomElementRegistry',
'XMLHttpRequestEventTarget', 'HTMLMediaElement', 'HTMLVideoElement',
'HTMLAudioElement', 'WebGL2RenderingContext',
+ 'SVGElement', 'SVGGraphicsElement', 'SVGGeometryElement', 'SVGPathElement',
+ 'SVGSVGElement',
];
var _desc = { value: undefined, writable: true, enumerable: false, configurable: true };
for (var _i = 0; _i < _names.length; _i++) {
@@ -1551,6 +1553,7 @@ class Node {
}
if (c._shadowParent) c._shadowParent.removeChild(c);
_dom("append_child", this._nid, c._nid);
+ _registerWindowNamedTree(c);
if (globalThis.__mutationObservers?.length) globalThis.__notifyMutation('childList', this._nid, [c._nid], []);
__prepareInsertedSubtree(c);
if (c instanceof Element && c.tagName === 'LINK') {
@@ -1560,6 +1563,7 @@ class Node {
}
removeChild(c) {
if (!c) return c;
+ const removedWindowNames = _windowNamedNamesInTree(c);
const linkedStyle = c instanceof Element
? _linkedStylesheetNodes.get(c)
: null;
@@ -1568,6 +1572,7 @@ class Node {
_linkedStylesheetNodes.delete(c);
}
_dom("remove_child", c._nid);
+ _reconcileWindowNamedProperties(removedWindowNames);
if (globalThis.__mutationObservers?.length) globalThis.__notifyMutation('childList', this._nid, [], [c._nid]);
return c;
}
@@ -1580,8 +1585,11 @@ class Node {
return oldChild;
}
if (newChild._shadowParent) newChild._shadowParent.removeChild(newChild);
+ const removedWindowNames = _windowNamedNamesInTree(oldChild);
_dom("insert_before", newChild._nid, oldChild._nid);
_dom("remove_child", oldChild._nid);
+ _registerWindowNamedTree(newChild);
+ _reconcileWindowNamedProperties(removedWindowNames);
__prepareInsertedSubtree(newChild);
return oldChild;
}
@@ -1595,6 +1603,7 @@ class Node {
}
if (n._shadowParent) n._shadowParent.removeChild(n);
_dom("insert_before", n._nid, ref._nid);
+ _registerWindowNamedTree(n);
__prepareInsertedSubtree(n);
return n;
}
@@ -2471,12 +2480,18 @@ class Element extends Node {
// `dangerouslySetInnerHTML`, vue-style content swaps) silently bypass
// every MutationObserver subscriber and downstream hydration / polling
// logic stalls.
+ const previousWindowNames = _windowNamedNamesInTree(this);
let oldChildren = [];
let newChildren = [];
if (globalThis.__mutationObservers?.length) {
oldChildren = _domParse("child_nodes", this._nid) || [];
}
_dom("set_inner_html", this._nid, String(v ?? ""));
+ // HTML fragment parsing can introduce IDs without calling the JS
+ // setAttribute path. Register those elements for Window named access
+ // before script can synchronously read `window.someId`.
+ _registerWindowNamedTree(this);
+ _reconcileWindowNamedProperties(previousWindowNames);
if (globalThis.__mutationObservers?.length) {
newChildren = _domParse("child_nodes", this._nid) || [];
globalThis.__notifyMutation('childList', this._nid, newChildren, oldChildren);
@@ -2584,8 +2599,19 @@ class Element extends Node {
setAttribute(n, v) {
n = _htmlAttrName(this, n);
const popoverPrev = (n === "popover") ? this.popover : undefined;
+ const previousWindowName = (n === "id" || n === "name")
+ ? this.getAttribute(n)
+ : null;
const value = String(v);
_dom("set_attribute", this._nid, n + "\0" + value);
+ if (n === "id" || (n === "name" && _windowNameEligibleElement(this))) {
+ if (this.getRootNode() === globalThis.document) {
+ _ensureWindowNamedProperty(value);
+ }
+ if (previousWindowName && previousWindowName !== value) {
+ _reconcileWindowNamedProperty(previousWindowName);
+ }
+ }
if (n === "style") this._style._replaceFromAttribute(value);
if (popoverPrev !== undefined) this._popoverTypeMaybeChanged(popoverPrev);
if (globalThis.__mutationObservers?.length) globalThis.__notifyMutation('attributes', this._nid, [], [], n);
@@ -2611,7 +2637,14 @@ class Element extends Node {
removeAttribute(n) {
n = _htmlAttrName(this, n);
const popoverPrev = (n === "popover") ? this.popover : undefined;
+ const previousWindowName = (n === "id" || n === "name")
+ ? this.getAttribute(n)
+ : null;
_dom("remove_attribute", this._nid, n);
+ if (previousWindowName
+ && (n === "id" || (n === "name" && _windowNameEligibleElement(this)))) {
+ _reconcileWindowNamedProperty(previousWindowName);
+ }
if (n === "style") this._style._replaceFromAttribute("");
if (popoverPrev !== undefined) this._popoverTypeMaybeChanged(popoverPrev);
if (this.localName === "source"
@@ -5252,6 +5285,15 @@ globalThis.VTTCue = VTTCue;
function _elementClassFor(nid) {
const tag = _domParse("tag_name", nid);
+ // HTML tagName values are ASCII-uppercase. Foreign SVG names retain their
+ // case, so keep the common HTML path fast and only inspect the native
+ // namespace for possible SVG wrappers.
+ if (tag && tag !== tag.toUpperCase()
+ && _domParse("namespace_uri", nid) === "http://www.w3.org/2000/svg") {
+ if (tag === "path" && globalThis.SVGPathElement) return globalThis.SVGPathElement;
+ if (tag === "svg" && globalThis.SVGSVGElement) return globalThis.SVGSVGElement;
+ if (globalThis.SVGElement) return globalThis.SVGElement;
+ }
if (tag === "FORM" && globalThis.HTMLFormElement) return globalThis.HTMLFormElement;
if (tag === "IMG") return HTMLImageElement;
if (tag === "CANVAS" && globalThis.HTMLCanvasElement) return globalThis.HTMLCanvasElement;
@@ -9597,8 +9639,16 @@ Object.defineProperty(SVGAnimatedString.prototype, 'animVal', {
Object.defineProperty(SVGAnimatedString.prototype, Symbol.toStringTag, { value: 'SVGAnimatedString', configurable: true });
_markNative(SVGAnimatedString);
-globalThis.SVGElement = Element;
-globalThis.SVGSVGElement = Element;
+class SVGElement extends Element {}
+class SVGGraphicsElement extends SVGElement {}
+class SVGGeometryElement extends SVGGraphicsElement {}
+class SVGPathElement extends SVGGeometryElement {}
+class SVGSVGElement extends SVGGraphicsElement {}
+globalThis.SVGElement = SVGElement;
+globalThis.SVGGraphicsElement = SVGGraphicsElement;
+globalThis.SVGGeometryElement = SVGGeometryElement;
+globalThis.SVGPathElement = SVGPathElement;
+globalThis.SVGSVGElement = SVGSVGElement;
globalThis.CharacterData = CharacterData;
globalThis.Text = Text;
globalThis.Comment = Comment;
@@ -9714,6 +9764,131 @@ function _nodeList(els) {
nl.length = els.length;
return nl;
}
+
+// Window named access. HTML exposes every element id, plus the name of a
+// small legacy set of HTML elements, as properties of the WindowProxy. V8's
+// global object cannot be replaced with a WindowProxy after snapshot startup,
+// so install lazy accessors for the supported names present in this document.
+// The accessor resolves against the live tree: one match returns that element
+// (or an iframe's Window), while duplicates return a live-shaped
+// HTMLCollection in tree order.
+const _windowNamedPropertyNames = new Set();
+const _windowNamedNameTags = new Set(["embed", "form", "iframe", "img", "object"]);
+
+function _windowNameEligibleElement(element) {
+ return !!element
+ && element.namespaceURI === "http://www.w3.org/1999/xhtml"
+ && _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;
+}
+
+function _windowNamedValue(name) {
+ const matches = _windowNamedCandidates(name);
+ if (matches.length === 0) return undefined;
+ if (matches.length > 1) return HTMLCollection._from(matches);
+ const element = matches[0];
+ return element.localName === "iframe" && element.contentWindow
+ ? element.contentWindow
+ : element;
+}
+
+function _ensureWindowNamedProperty(name) {
+ name = String(name || "");
+ if (!name || _windowNamedPropertyNames.has(name)) return;
+ // Existing own Window properties win over named elements.
+ if (Object.prototype.hasOwnProperty.call(globalThis, name)) return;
+ try {
+ Object.defineProperty(globalThis, name, {
+ get() { return _windowNamedValue(name); },
+ configurable: true,
+ enumerable: true,
+ });
+ _windowNamedPropertyNames.add(name);
+ } catch (_error) {}
+}
+
+function _reconcileWindowNamedProperty(name) {
+ if (!_windowNamedPropertyNames.has(name)) return;
+ if (_windowNamedCandidates(name).length !== 0) return;
+ try { delete globalThis[name]; } catch (_error) {}
+ _windowNamedPropertyNames.delete(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;
+}
+
+function _registerWindowNamedTree(root) {
+ // Window named access only considers the document tree. Detached nodes and
+ // attached shadow trees must not manufacture own Window properties.
+ if (!root || root.getRootNode() !== globalThis.document) return;
+ const names = _windowNamedNamesInTree(root);
+ for (const name of names) _ensureWindowNamedProperty(name);
+}
+
+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);
+ }
+ }
+ for (const name of names) {
+ if (_windowNamedPropertyNames.has(name) && !present.has(name)) {
+ try { delete globalThis[name]; } catch (_error) {}
+ _windowNamedPropertyNames.delete(name);
+ }
+ }
+}
+
globalThis.DOMTokenList = DOMTokenList;
// NodeList is its own type, not an Array subclass: in a real browser
// Array.isArray(nodeList) is false and Object.prototype.toString reports
@@ -12551,6 +12726,9 @@ globalThis.__obscura_init = function() {
// canonical so getRootNode(), isConnected, and identity comparisons return
// the same Document object exposed as globalThis.document.
_cache.set(documentNid, globalThis.document);
+ const previousWindowNames = new Set(_windowNamedPropertyNames);
+ _registerWindowNamedTree(globalThis.document.documentElement);
+ _reconcileWindowNamedProperties(previousWindowNames);
const scr = _fp('screen');
const sw = scr[0], sh = scr[1];
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index b10ddaa6..fa4197c9 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -3582,6 +3582,301 @@ mod tests {
);
}
+ #[test]
+ fn clone_node_deep_preserves_context_sensitive_elements() {
+ // A <tr> is not a valid child of <div>, so cloning through a throwaway
+ // <div>.innerHTML dropped it and returned null. A structural clone keeps it.
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let tag = rt
+ .evaluate("(document.createElement('tr').cloneNode(true) || {}).tagName || 'NULL'")
+ .unwrap();
+ assert_eq!(tag, serde_json::json!("TR"));
+ let td = rt
+ .evaluate("(document.createElement('td').cloneNode(true) || {}).tagName || 'NULL'")
+ .unwrap();
+ assert_eq!(td, serde_json::json!("TD"));
+ }
+
+ #[test]
+ fn clone_node_deep_copies_children_and_attributes() {
+ let mut rt = setup_runtime(r#"<html><body><ul id="l"><li class="a">one</li><li class="b">two</li></ul></body></html>"#);
+ let out = rt
+ .evaluate(
+ "(function(){var c=document.getElementById('l').cloneNode(true); return c.children.length + '|' + c.children[0].className + '|' + c.children[1].textContent;})()",
+ )
+ .unwrap();
+ assert_eq!(out, serde_json::json!("2|a|two"));
+ }
+
+ #[test]
+ fn test_clone_node_deep() {
+ let mut rt = setup_runtime(r#"<div id="src"><p>A</p><p>B</p></div>"#);
+ rt.execute_script(
+ "test",
+ r#"
+ var src = document.getElementById('src');
+ var clone = src.cloneNode(true);
+ document.body.appendChild(clone);
+ "#,
+ )
+ .unwrap();
+ let count = rt.evaluate("document.querySelectorAll('p').length").unwrap();
+ assert!(
+ count.as_f64().unwrap() as i64 >= 4,
+ "Deep clone should duplicate <p> children, got: {}",
+ count
+ );
+ }
+
+ #[test]
+ fn clone_node_deep_preserves_table_rows() {
+ let mut rt = setup_runtime(
+ r#"<html><body><table id="t"><tbody><tr><td>1</td><td>2</td></tr></tbody></table></body></html>"#,
+ );
+ // Navigate the detached clone directly (querySelector does not traverse
+ // detached subtrees). tbody > tr > (td, td).
+ let out = rt
+ .evaluate(
+ "(function(){var tb=document.querySelector('#t tbody').cloneNode(true); var tr=tb.children[0]; return tr.tagName + '|' + tr.children.length + '|' + tr.children[1].textContent;})()",
+ )
+ .unwrap();
+ assert_eq!(out, serde_json::json!("TR|2|2"));
+ }
+
+ #[test]
+ fn clone_node_shallow_copies_attributes_without_children() {
+ let mut rt = setup_runtime(r#"<html><body><div id="d" data-x="7"><span>kid</span></div></body></html>"#);
+ let out = rt
+ .evaluate(
+ "(function(){var c=document.getElementById('d').cloneNode(false); return c.getAttribute('data-x') + '|' + c.childNodes.length;})()",
+ )
+ .unwrap();
+ assert_eq!(out, serde_json::json!("7|0"));
+ }
+
+ #[test]
+ fn clone_node_copies_js_assigned_inline_styles() {
+ let mut rt = setup_runtime("<html><body><div id='d'></div></body></html>");
+ let out = rt
+ .evaluate(
+ "(function(){var d=document.getElementById('d');d.style.color='red';d.style.fontSize='12px';var c=d.cloneNode(false);return c.style.color+'|'+c.style.fontSize+'|'+c.style.cssText;})()",
+ )
+ .unwrap();
+ assert_eq!(out, serde_json::json!("red|12px|color: red; font-size: 12px;"));
+ }
+
+ #[test]
+ fn clone_node_deep_copies_template_content() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let out = rt
+ .evaluate(
+ "(function(){var t=document.createElement('template');t.content.appendChild(document.createElement('option')).textContent='choice';var c=t.cloneNode(true);return c.content.childNodes.length+'|'+c.content.firstChild.tagName+'|'+c.content.firstChild.textContent;})()",
+ )
+ .unwrap();
+ assert_eq!(out, serde_json::json!("1|OPTION|choice"));
+ }
+
+ #[test]
+ fn insert_adjacent_html_parses_table_fragments() {
+ let mut rt = setup_runtime(
+ r#"<html><body><table id="t"><tbody id="tb"></tbody></table></body></html>"#,
+ );
+ let out = rt
+ .evaluate("(function(){var tb=document.getElementById('tb'); tb.insertAdjacentHTML('beforeend','<tr><td>1</td><td>2</td></tr>'); var tr=tb.firstElementChild; return tr ? (tr.tagName+':'+tr.children.length) : 'NULL';})()")
+ .unwrap();
+ assert_eq!(out, serde_json::json!("TR:2"));
+ }
+
+ #[test]
+ fn insert_adjacent_html_position_is_case_insensitive() {
+ let mut rt = setup_runtime(r#"<html><body><div id="host"><span>base</span></div></body></html>"#);
+ let out = rt
+ .evaluate("(function(){var h=document.getElementById('host'); h.insertAdjacentHTML('BeforeEnd','<b>x</b>'); return h.lastElementChild ? h.lastElementChild.tagName : 'NULL';})()")
+ .unwrap();
+ assert_eq!(out, serde_json::json!("B"));
+ }
+
+ #[test]
+ fn insert_adjacent_html_rejects_invalid_position() {
+ let mut rt = setup_runtime(r#"<html><body><div id="host"></div></body></html>"#);
+ let out = rt
+ .evaluate("(function(){var h=document.getElementById('host'); try { h.insertAdjacentHTML('nope','<b>x</b>'); return 'no-throw'; } catch(e){ return e.name; }})()")
+ .unwrap();
+ assert_eq!(out, serde_json::json!("SyntaxError"));
+ }
+
+ #[test]
+ fn insert_adjacent_html_keeps_leading_comments_in_table_contexts() {
+ let mut rt = setup_runtime(
+ r#"<html><body><table><tbody id="tb"><tr id="row"></tr></tbody></table></body></html>"#,
+ );
+ let out = rt
+ .evaluate(
+ "(function(){var tb=document.getElementById('tb');tb.insertAdjacentHTML('beforeend','<!--m--><tr><td>v</td></tr>');var row=document.getElementById('row');row.insertAdjacentHTML('beforeend','<!--n--><td>x</td>');return Array.from(tb.childNodes).map(function(n){return n.nodeName}).join('|')+';'+Array.from(row.childNodes).map(function(n){return n.nodeName}).join('|');})()",
+ )
+ .unwrap();
+ assert_eq!(out, serde_json::json!("TR|#comment|TR;#comment|TD"));
+ }
+
+ #[test]
+ fn insert_adjacent_html_uses_the_insertion_element_as_context() {
+ let mut rt = setup_runtime(
+ r#"<html><body><div id="d"></div><table id="table"><tbody id="tb"></tbody></table></body></html>"#,
+ );
+ let out = rt
+ .evaluate(
+ "(function(){var d=document.getElementById('d');d.insertAdjacentHTML('beforeend','<tr><td>v</td></tr>');var table=document.getElementById('table');table.insertAdjacentHTML('beforeend','<tr><td>x</td></tr>');var tb=document.getElementById('tb');tb.insertAdjacentHTML('beforeend','<tr><td>y</td></tr>tail');return d.firstChild.nodeName+':'+d.textContent+';'+table.lastElementChild.tagName+';'+Array.from(tb.childNodes).map(function(n){return n.nodeName+(n.data?':'+n.data:'')}).join('|');})()",
+ )
+ .unwrap();
+ assert_eq!(out, serde_json::json!("#text:v;TBODY;TR|#text:tail"));
+ }
+
+ #[test]
+ fn set_attribute_ns_is_retrievable_by_namespace_and_local_name() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let v = rt
+ .evaluate("(function(){var s=document.createElementNS('http://www.w3.org/2000/svg','svg'); s.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','#g'); return s.getAttributeNS('http://www.w3.org/1999/xlink','href');})()")
+ .unwrap();
+ assert_eq!(v, serde_json::json!("#g"));
+ }
+
+ #[test]
+ fn created_foreign_element_keeps_native_qualified_name_through_clone() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let v = rt
+ .evaluate(
+ "(function(){const ns='http://www.w3.org/2000/svg';const el=document.createElementNS(ns,'linearGradient');const clone=el.cloneNode(true);return [el.namespaceURI,el.localName,el.tagName,el.nodeName,clone.namespaceURI,clone.localName,clone.outerHTML].join('|');})()",
+ )
+ .unwrap();
+ assert_eq!(
+ v,
+ serde_json::json!(
+ "http://www.w3.org/2000/svg|linearGradient|linearGradient|linearGradient|http://www.w3.org/2000/svg|linearGradient|<linearGradient></linearGradient>"
+ )
+ );
+ }
+
+ #[test]
+ fn svg_path_uses_the_standard_interface_chain() {
+ let mut rt = setup_runtime(
+ r#"<html><body><svg><path id="shape" d="M0 0L1 1"></path></svg></body></html>"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ const parsed = document.getElementById("shape");
+ SVGPathElement.prototype.polyfillProbe = () => "path";
+ const created = document.createElementNS(
+ "http://www.w3.org/2000/svg", "path"
+ );
+ const div = document.createElement("div");
+ return [
+ parsed.constructor.name,
+ parsed instanceof SVGPathElement,
+ parsed instanceof SVGGeometryElement,
+ parsed instanceof SVGGraphicsElement,
+ parsed instanceof SVGElement,
+ parsed instanceof Element,
+ created instanceof SVGPathElement,
+ Object.getPrototypeOf(SVGPathElement.prototype) === SVGGeometryElement.prototype,
+ Object.getPrototypeOf(SVGGeometryElement.prototype) === SVGGraphicsElement.prototype,
+ Object.getPrototypeOf(SVGGraphicsElement.prototype) === SVGElement.prototype,
+ Object.getPrototypeOf(SVGElement.prototype) === Element.prototype,
+ parsed.polyfillProbe(),
+ typeof div.polyfillProbe
+ ];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([
+ "SVGPathElement",
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ "path",
+ "undefined"
+ ])
+ );
+ }
+
+ #[test]
+ fn foreign_inner_html_and_contextual_fragments_keep_svg_namespace() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let v = rt
+ .evaluate(
+ "(function(){const ns='http://www.w3.org/2000/svg';const svg=document.createElementNS(ns,'svg');svg.innerHTML='<linearGradient id=paint></linearGradient>';const range=document.createRange();range.selectNodeContents(svg);const fragment=range.createContextualFragment('<circle></circle>');const circle=fragment.firstElementChild;return [svg.firstElementChild.namespaceURI,svg.firstElementChild.localName,circle.namespaceURI,circle.localName].join('|');})()",
+ )
+ .unwrap();
+ assert_eq!(
+ v,
+ serde_json::json!(
+ "http://www.w3.org/2000/svg|linearGradient|http://www.w3.org/2000/svg|circle"
+ )
+ );
+ }
+
+ #[test]
+ fn remove_attribute_ns_removes_by_namespace() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let v = rt
+ .evaluate("(function(){var s=document.createElementNS('http://www.w3.org/2000/svg','svg'); s.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','#g'); s.removeAttributeNS('http://www.w3.org/1999/xlink','href'); return s.getAttributeNS('http://www.w3.org/1999/xlink','href');})()")
+ .unwrap();
+ assert_eq!(v, serde_json::json!(null));
+ }
+
+ #[test]
+ fn get_attribute_ns_reads_plain_attributes_with_null_namespace() {
+ // Backward-compat: getAttributeNS(null, name) still reads a plain attr.
+ let mut rt = setup_runtime(r#"<html><body><div id="d" title="hi"></div></body></html>"#);
+ let v = rt
+ .evaluate("document.getElementById('d').getAttributeNS(null,'title')")
+ .unwrap();
+ assert_eq!(v, serde_json::json!("hi"));
+ }
+
+ #[test]
+ fn namespaced_attribute_keeps_its_qualified_name() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let v = rt
+ .evaluate("(function(){var s=document.createElementNS('http://www.w3.org/2000/svg','svg');s.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','#g');return s.getAttribute('xlink:href')+'|'+s.getAttributeNames()[0]+'|'+s.outerHTML;})()")
+ .unwrap();
+ assert_eq!(v, serde_json::json!("#g|xlink:href|<svg xlink:href=\"#g\"></svg>"));
+ }
+
+ #[test]
+ fn parsed_xlink_attribute_is_available_through_both_apis() {
+ let mut rt = setup_runtime(
+ r##"<html><body><svg><use id="u" xlink:href="#icon"></use></svg></body></html>"##,
+ );
+ let v = rt
+ .evaluate("(function(){var u=document.getElementById('u');return u.getAttribute('xlink:href')+'|'+u.getAttributeNS('http://www.w3.org/1999/xlink','href')+'|'+u.getAttributeNames().join(',');})()")
+ .unwrap();
+ assert_eq!(v, serde_json::json!("#icon|#icon|id,xlink:href"));
+ }
+
+ #[test]
+ fn set_attribute_ns_validates_namespace_constraints() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let v = rt
+ .evaluate("(function(){var e=document.createElement('div'),out=[];for(const args of [[null,'x:y'],['urn:test','a:b:c'],['urn:test','xml:lang'],['urn:test','xmlns:x']]){try{e.setAttributeNS(args[0],args[1],'v');out.push('none')}catch(err){out.push(err.name)}}return out.join('|');})()")
+ .unwrap();
+ assert_eq!(
+ v,
+ serde_json::json!(
+ "NamespaceError|InvalidCharacterError|NamespaceError|NamespaceError"
+ )
+ );
+ }
+
#[test]
fn throwing_custom_element_constructor_marks_upgrade_failed_without_connecting() {
let mut rt = setup_runtime(
@@ -3727,6 +4022,115 @@ mod tests {
);
}
+ #[test]
+ fn window_named_access_exposes_ids_and_eligible_names() {
+ let mut rt = setup_runtime(
+ r#"<html><body>
+ <script id="payload" type="application/json">{"ready":true}</script>
+ <div id="duplicate"></div><span id="duplicate"></span>
+ <form name="login"></form><img name="hero">
+ <div name="not-exposed"></div>
+ </body></html>"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ return [
+ window.payload === document.getElementById("payload"),
+ window.payload.text,
+ window.duplicate instanceof HTMLCollection,
+ window.duplicate.length,
+ window.login === document.querySelector("form"),
+ window.hero === document.querySelector("img"),
+ typeof window["not-exposed"]
+ ];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([
+ true,
+ "{\"ready\":true}",
+ true,
+ 2,
+ true,
+ true,
+ "undefined"
+ ])
+ );
+ }
+
+ #[test]
+ fn window_named_access_tracks_dynamic_ids_and_fragment_parsing() {
+ let mut rt = setup_runtime("<html><body><div id='host'></div></body></html>");
+ let result = rt
+ .evaluate(
+ r#"
+ const made = document.createElement("section");
+ made.id = "dynamicName";
+ const detachedIdAbsent = !("dynamicName" in window);
+ document.body.appendChild(made);
+ const first = window.dynamicName === made;
+ made.id = "renamedDynamic";
+ const renamed = !("dynamicName" in window)
+ && window.renamedDynamic === made;
+ document.body.removeChild(made);
+ const removed = !("renamedDynamic" in window);
+ document.body.appendChild(made);
+ const reattached = window.renamedDynamic === made;
+ document.getElementById("host").innerHTML =
+ "<script id='parsedName'>payload</script>";
+ const parsed = window.parsedName === document.getElementById("parsedName")
+ && window.parsedName.text === "payload";
+ document.getElementById("host").innerHTML = "";
+ const subtree = document.createElement("div");
+ subtree.innerHTML = "<svg><path id='nestedSvg' name='svgName'></path></svg>";
+ const detachedNestedAbsent = !("nestedSvg" in window);
+ document.body.appendChild(subtree);
+ const nested = window.nestedSvg === subtree.querySelector("path")
+ && typeof window.svgName === "undefined";
+ document.body.removeChild(subtree);
+ const nestedRemoved = !("nestedSvg" in window);
+ document.body.appendChild(subtree);
+ const shadowHost = document.createElement("div");
+ const shadowRoot = shadowHost.attachShadow({ mode: "open" });
+ const shadowChild = document.createElement("span");
+ shadowChild.id = "shadowOnly";
+ shadowRoot.appendChild(shadowChild);
+ document.body.appendChild(shadowHost);
+ const originalFetch = window.fetch;
+ const collision = document.createElement("div");
+ collision.id = "fetch";
+ document.body.appendChild(collision);
+ document.body.removeChild(collision);
+ return [
+ detachedIdAbsent,
+ first,
+ renamed,
+ removed,
+ reattached,
+ parsed,
+ !("parsedName" in window),
+ detachedNestedAbsent,
+ nested,
+ nestedRemoved,
+ window.nestedSvg === subtree.querySelector("path"),
+ !("shadowOnly" in window),
+ window.fetch === originalFetch
+ ];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([
+ true, true, true, true, true, true, true, true, true, true, true, true,
+ true
+ ])
+ );
+ }
+
#[test]
fn explicit_viewport_is_distinct_from_fingerprinted_screen() {
let dom = parse_html("<html><body></body></html>");