Skip to content

The headless browser for AI agents and web scraping

perf(js): allocate inline styles on demand

SGavrl3a9eb06f2bcf
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 46fd19f7..3d76110c 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -1791,19 +1791,22 @@ function _serializeCss(props) {
return e.length ? e.map(([k, v]) => `${k}: ${v}`).join("; ") + ";" : "";
}
+const _styleDefineProperty = Object.defineProperty;
+const _styleProxyConstructor = Proxy;
+const _styleReflectApply = Reflect.apply;
class CSSStyleDeclaration {
constructor(owner, onChange) {
// Non-enumerable so they never leak through the proxy's own-key traps.
- Object.defineProperty(this, "_props", { value: {}, writable: true, enumerable: false, configurable: true });
+ _styleDefineProperty(this, "_props", { value: {}, writable: true, enumerable: false, configurable: true });
// The owner Element, if any. A live declaration reflects that element's
// `style` content attribute in both directions; an owner-less declaration
// (getComputedStyle fallback, stylesheet rules) is purely in-memory.
- Object.defineProperty(this, "_owner", { value: owner || null, writable: true, enumerable: false, configurable: true });
- Object.defineProperty(this, "_onChange", { value: onChange || null, writable: true, enumerable: false, configurable: true });
+ _styleDefineProperty(this, "_owner", { value: owner || null, writable: true, enumerable: false, configurable: true });
+ _styleDefineProperty(this, "_onChange", { value: onChange || null, writable: true, enumerable: false, configurable: true });
// Load the content attribute only when style is first observed. Keeping
// this as a primitive avoids allocating a separate sync object for every
// wrapped element.
- Object.defineProperty(this, "_loaded", { value: !owner, writable: true, enumerable: false, configurable: true });
+ _styleDefineProperty(this, "_loaded", { value: !owner, writable: true, enumerable: false, configurable: true });
}
// Pull the initial `style` attribute once. Later attribute mutations update
// the declaration directly from Element.setAttribute/removeAttribute, so
@@ -1871,7 +1874,7 @@ class CSSStyleDeclaration {
item(i) { this._pull(); return Object.keys(this._props)[i] || ""; }
}
-const _styleProxy = (decl) => new Proxy(decl, {
+const _styleProxyHandler = {
get(t, p) {
if (typeof p === "symbol" || p in t) return t[p];
if (/^\d+$/.test(p)) return t.item(+p);
@@ -1913,7 +1916,8 @@ const _styleProxy = (decl) => new Proxy(decl, {
}
return undefined;
},
-});
+};
+const _styleProxy = (decl) => new _styleProxyConstructor(decl, _styleProxyHandler);
// Clone a single node (no children), used by Node.cloneNode. Elements are built
// with createElement/createElementNS and their content attributes copied, so no
@@ -4025,6 +4029,21 @@ function _renderedInnerText(element) {
.replace(/^[ \n\t]+|[ \n\t]+$/g, '');
}
+const _elementStyles = new WeakMap();
+const _elementStyleGet = _elementStyles.get.bind(_elementStyles);
+const _elementStyleSet = _elementStyles.set.bind(_elementStyles);
+function _elementStyle(element) {
+ let style = _elementStyleGet(element);
+ if (!style) {
+ // A borrowed getter must return the owning realm's same declaration.
+ const member = _documentRealmMember(element, 'elementStyle');
+ style = member ? _styleReflectApply(member, element, [])
+ : _styleProxy(new CSSStyleDeclaration(element));
+ _elementStyleSet(element, style);
+ }
+ return style;
+}
+
class Element extends Node {
constructor(nid) {
const entry = _customElementConstructionStack[_customElementConstructionStack.length - 1];
@@ -4042,7 +4061,6 @@ class Element extends Node {
Object.setPrototypeOf(upgrading, new.target.prototype);
return upgrading;
}
- this._style = _styleProxy(new CSSStyleDeclaration(this));
}
// Element wrappers always back a nodeType-1 node (_wrap/_wrapEl only build an
// Element for element nodes, and node ids are never freed-and-reused), so this
@@ -4233,8 +4251,8 @@ class Element extends Node {
this.setAttribute("for", String(v));
}
}
- get style() { return this._style; }
- set style(v) { if (typeof v === "string") this._style.cssText = v; }
+ get style() { return _elementStyle(this); }
+ set style(v) { if (typeof v === "string") _elementStyle(this).cssText = v; }
getAttribute(n) {
n = _htmlAttrName(this, n);
// Script-created elements start with a provably empty attribute set. Keep
@@ -4272,7 +4290,7 @@ class Element extends Node {
_reconcileWindowNamedProperty(previousWindowName);
}
}
- if (n === "style") this._style._replaceFromAttribute(value);
+ if (n === "style") _elementStyleGet(this)?._replaceFromAttribute(value);
if (n === "onload" && _isWindowReflectingBodyElement(this)) {
_windowOnloadOverrideSet = false;
_windowOnloadOverride = null;
@@ -4305,7 +4323,7 @@ class Element extends Node {
// instead of maintaining a second, subtly different key space here.
this._nullNamespaceAttrs = null;
if (ns === '' && n === 'srcdoc' && this.localName === 'iframe') this._loadIframeSrcdoc(true);
- if (ns === "" && n === "style") this._style._replaceFromAttribute(value);
+ if (ns === "" && n === "style") _elementStyleGet(this)?._replaceFromAttribute(value);
}
removeAttribute(n) {
n = _htmlAttrName(this, n);
@@ -4325,7 +4343,7 @@ class Element extends Node {
&& (n === "id" || (n === "name" && _windowNameEligibleElement(this)))) {
_reconcileWindowNamedProperty(previousWindowName);
}
- if (n === "style") this._style._replaceFromAttribute("");
+ if (n === "style") _elementStyleGet(this)?._replaceFromAttribute("");
if (n === "onload" && _isWindowReflectingBodyElement(this)) {
_windowOnloadOverrideSet = false;
_windowOnloadOverride = null;
@@ -4352,7 +4370,7 @@ class Element extends Node {
if (observedOldValue !== null) _queueAttributeMutationRecord(this, n, ns || null, observedOldValue);
this._nullNamespaceAttrs = null;
if (ns === '' && n === 'srcdoc' && this.localName === 'iframe') this._loadIframeSrc(this.getAttribute('src') || 'about:blank');
- if (ns === "" && n === "style") this._style._replaceFromAttribute("");
+ if (ns === "" && n === "style") _elementStyleGet(this)?._replaceFromAttribute("");
}
hasAttribute(n) { return this.getAttribute(n) !== null; }
hasAttributes() { return this.attributes.length > 0; }
@@ -18351,6 +18369,7 @@ const _documentMembers = Object.freeze(Object.fromEntries([
return _nativeElementClick.call(this, trusted ? _TRUSTED_ACTIVATION : undefined);
}],
['checkVisibility', Element.prototype.checkVisibility],
+ ['elementStyle', function() { return _elementStyle(this); }],
]));
globalThis.__obscura_init = function() {
diff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rs
index 31b70493..57c70ebe 100644
--- a/crates/obscura-js/src/frame.rs
+++ b/crates/obscura-js/src/frame.rs
@@ -451,6 +451,22 @@ mod tests {
runtime
}
+ #[test]
+ fn borrowed_style_getter_keeps_the_elements_declaration() {
+ let mut parent = page("https://parent.example/", "<html><body></body></html>");
+ let _frame = FrameRealm::new(&mut parent, 1, 0,
+ "https://parent.example/frame", "<html><body style='color: red'>Child</body></html>")
+ .expect("frame realm");
+ assert_eq!(parent.evaluate(r#"(() => {
+ const element = globalThis.__obscura_frameObjects[1].document.body;
+ const getter = Object.getOwnPropertyDescriptor(Element.prototype, 'style').get;
+ const borrowed = getter.call(element);
+ const same = borrowed === element.style;
+ element.setAttribute('style', 'color: blue');
+ return [same, borrowed.color, element.style.color];
+ })()"#).unwrap(), serde_json::json!([true, "blue", "blue"]));
+ }
+
#[test]
fn borrowed_content_type_getter_reads_the_frame_document() {
let mut parent = ObscuraJsRuntime::new();
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index a6d35538..1aca5f77 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -7090,6 +7090,63 @@ mod tests {
assert_eq!(rt.take_pending_history_traversal(), Some(0));
}
+ #[test]
+ fn element_style_is_not_replaced_by_a_page_expando() {
+ let mut rt = setup_runtime(
+ r#"<html><body><div id="d" style="color: red">hi</div></body></html>"#,
+ );
+ assert_eq!(rt.evaluate(r#"(() => {
+ const element = document.getElementById('d');
+ element._style = { color: 'poisoned' };
+ const style = element.style;
+ return [style instanceof CSSStyleDeclaration, style.color, style === element.style];
+ })()"#).unwrap(), serde_json::json!([true, "red", true]));
+ }
+
+ #[test]
+ fn first_element_style_access_ignores_replaced_page_intrinsics() {
+ let mut rt = setup_runtime("<html><body>Style</body></html>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const element = document.body;
+ const original = [globalThis.Proxy, Object.defineProperty,
+ WeakMap.prototype.get, WeakMap.prototype.set, Reflect.apply];
+ const fail = () => { throw new Error('page intrinsic called'); };
+ let style;
+ try {
+ globalThis.Proxy = fail;
+ Object.defineProperty = fail;
+ WeakMap.prototype.get = fail;
+ WeakMap.prototype.set = fail;
+ Reflect.apply = fail;
+ style = element.style;
+ } finally {
+ [globalThis.Proxy, Object.defineProperty, WeakMap.prototype.get,
+ WeakMap.prototype.set, Reflect.apply] = original;
+ }
+ return [style instanceof CSSStyleDeclaration, style === element.style];
+ })()"#).unwrap(), serde_json::json!([true, true]));
+ }
+
+ #[test]
+ fn element_style_first_read_observes_prior_attribute_mutations() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const element = document.createElement('div');
+ element.setAttribute('style', 'color: red');
+ element.removeAttributeNS(null, 'style');
+ element.setAttributeNS(null, 'style', 'color: blue');
+ const style = element.style;
+ const before = style.color;
+ element.style = 'color: green';
+ const assigned = style.color;
+ element.removeAttribute('style');
+ const removed = style.color;
+ style.color = 'purple';
+ return [before, assigned, removed, style === element.style,
+ element.getAttribute('style')];
+ })()"#).unwrap(), serde_json::json!(["blue", "green", "", true, "color: purple;"]));
+ }
+
#[test]
fn style_attribute_parses_into_style_object() {
// Inline styles present in the parsed HTML must be visible via el.style.*