Skip to content

The headless browser for AI agents and web scraping

fix(js): implement checkVisibility() and inherit computed visibility

Christian Marbachf019ebeb5a34
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index e18d4da4..dd5fbc56 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -5109,10 +5109,34 @@ class Element extends Node {
}
return new DOMRectList([this.getBoundingClientRect()]);
}
- // No layout engine: a stub that always returns true unblocks Playwright's
- // actionability polling. With a real layout we'd check display, visibility,
- // opacity and rect dimensions per spec.
- checkVisibility(opts) { return true; }
+ // CSSOM View checkVisibility(). Box existence is judged from display along
+ // the flattened ancestor chain rather than from geometry, since some
+ // visible inline elements report 0x0 rects (#722). Playwright calls this
+ // before every action, so render builds answer from the retained cascade
+ // in one native call.
+ checkVisibility(opts) {
+ if (!this.isConnected) return false;
+ const options = opts && typeof opts === 'object' ? opts : {};
+ const checkOpacity = !!(options.opacityProperty || options.checkOpacity);
+ const checkVisibilityCSS = !!(options.visibilityProperty || options.checkVisibilityCSS);
+ if (typeof __obscuraCore.ops.op_check_visibility === 'function') {
+ return __obscuraCore.ops.op_check_visibility(this._nid | 0, checkOpacity, checkVisibilityCSS);
+ }
+ // Without the renderer, computed style only reflects inline declarations,
+ // so read them directly and resolve inheritance of `visibility` here.
+ let visibility = '';
+ for (let el = this; el; el = el.parentElement || (el.parentNode && el.parentNode.host) || null) {
+ const style = el.style;
+ if (!style) continue;
+ const display = style.display;
+ if (display === 'none' || (el === this && display === 'contents')) return false;
+ if (checkOpacity && style.opacity !== '' && parseFloat(style.opacity) <= 0) return false;
+ if (!visibility && style.visibility && style.visibility !== 'inherit') {
+ visibility = style.visibility;
+ }
+ }
+ return !(checkVisibilityCSS && visibility && visibility !== 'visible');
+ }
// ARIA reflection properties. Without an accessibility tree we expose the
// raw aria-* attributes so Playwright's getByRole / getByLabel locators can
// at least find elements that author them explicitly.
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 18564d24..4297fab4 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -6119,6 +6119,7 @@ pub fn build_extension() -> Extension {
ops.push(op_resize_observer_measurements());
ops.push(op_intersection_observer_measurements());
ops.push(op_computed_style());
+ ops.push(op_check_visibility());
ops.push(op_css_supports());
ops.push(op_layout_metrics());
ops.push(op_element_scroll_metrics());
@@ -7238,6 +7239,34 @@ fn op_computed_style(state: &OpState, #[string] nid_str: String) -> String {
serde_json::Value::Object(object).to_string()
}
+/// `Element.checkVisibility()` in one native call. Walking ancestors through
+/// `getComputedStyle()` cost a JS proxy per ancestor, and Playwright calls
+/// this before every action.
+#[cfg(feature = "render")]
+#[op2(fast)]
+fn op_check_visibility(
+ state: &OpState,
+ nid: u32,
+ check_opacity: bool,
+ check_visibility_css: bool,
+) -> bool {
+ let shared = state.borrow::<SharedState>().clone();
+ let mut gs = shared.borrow_mut();
+ sample_live_document_animations(&mut gs);
+ if ensure_prepared_render(&mut gs).is_none() {
+ return false;
+ }
+ let (Some(prepared), Some(dom)) = (gs.prepared_render.as_ref(), gs.dom.as_ref()) else {
+ return false;
+ };
+ prepared.check_visibility(
+ dom,
+ obscura_dom::tree::NodeId::new(nid),
+ check_opacity,
+ check_visibility_css,
+ )
+}
+
/// Use the renderer's declaration parser as the single feature-query source
/// of truth. Keeping this bridge synchronous and state-free makes the common
/// two-argument `CSS.supports()` overload a single native call.
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 0346a104..f4001e82 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -19836,9 +19836,7 @@ mod tests {
/// Playwright >= 1.25 calls `element.checkVisibility(...)` before every
/// input event. If the method isn't defined Playwright retries until its
- /// action timeout fires. Without a layout engine we can't compute it
- /// properly, so the stub always returns true — still strictly better
- /// than the undefined path.
+ /// action timeout fires, so it must exist and be true for plain elements.
#[test]
fn element_check_visibility_is_callable() {
let mut rt = setup_runtime(r#"<div id="x">x</div>"#);
@@ -19853,6 +19851,52 @@ mod tests {
assert_eq!(typeof_method, serde_json::json!("function"));
}
+ /// Issue #1067: checkVisibility() follows the CSSOM View algorithm:
+ /// elements without a box (display:none on self or an ancestor,
+ /// display:contents, disconnected) are hidden, and the opacity /
+ /// visibility options are honored, including their legacy aliases.
+ #[test]
+ fn element_check_visibility_follows_css_boxes_and_options() {
+ let mut rt = setup_runtime(
+ r#"
+ <div style="display:none"><a id="a" href="/x">hidden</a></div>
+ <div style="visibility:hidden"><a id="b" href="/x">invisible</a></div>
+ <div style="opacity:0"><span id="c">transparent</span></div>
+ <span id="e" style="display:contents">contents</span>
+ <span id="f" style="display:none">self none</span>
+ <div style="visibility:hidden"><span id="g" style="visibility:visible">back</span></div>
+ <a id="v" href="/x">visible</a>
+ "#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ const $ = id => document.getElementById(id);
+ return [
+ $('a').checkVisibility(),
+ $('b').checkVisibility(),
+ $('b').checkVisibility({visibilityProperty: true}),
+ $('b').checkVisibility({checkVisibilityCSS: true}),
+ $('c').checkVisibility(),
+ $('c').checkVisibility({opacityProperty: true}),
+ $('c').checkVisibility({checkOpacity: true}),
+ $('e').checkVisibility(),
+ $('f').checkVisibility(),
+ $('g').checkVisibility({visibilityProperty: true}),
+ $('v').checkVisibility({visibilityProperty: true, opacityProperty: true}),
+ document.createElement('div').checkVisibility(),
+ ];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([
+ false, true, false, false, true, false, false, false, false, true, true, false
+ ])
+ );
+ }
+
/// Playwright's `getByRole` / `getByLabel` locators resolve via ARIA
/// reflection properties. Without the getters those locators always
/// fail. Reflect the underlying aria-* attributes.
diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rs
index 90bea55e..32e45efe 100644
--- a/crates/obscura-render/src/dom.rs
+++ b/crates/obscura-render/src/dom.rs
@@ -1043,6 +1043,7 @@ impl DomLayout {
};
let visibility_hidden = style.visibility_hidden.unwrap_or(parent_state.0);
let opacity_zero = parent_state.1 || style.opacity.is_some_and(|value| value <= 0.0);
+ style.visibility_hidden_computed = visibility_hidden;
style.effectively_invisible = visibility_hidden || opacity_zero;
if let Some(pseudo) = style.before_pseudo.as_deref_mut() {
pseudo.effectively_invisible = style.effectively_invisible;
@@ -5539,6 +5540,7 @@ fn layout_dom_once(
None => style.text_indent = Some(inh.text_indent),
}
inh.visibility_hidden = style.visibility_hidden.unwrap_or(inh.visibility_hidden);
+ style.visibility_hidden_computed = inh.visibility_hidden;
match style.pointer_events_none {
Some(value) => inh.pointer_events_none = value,
None => style.pointer_events_none = Some(inh.pointer_events_none),
diff --git a/crates/obscura-render/src/lib.rs b/crates/obscura-render/src/lib.rs
index 0992e406..12b9874e 100644
--- a/crates/obscura-render/src/lib.rs
+++ b/crates/obscura-render/src/lib.rs
@@ -1457,6 +1457,11 @@ pub struct LayoutStyle {
/// ancestor's `opacity` is zero. Fractional values remain paintable and
/// are isolated into composited groups by the paint pass.
pub effectively_invisible: bool,
+ /// Resolved during the inheritance pass: the computed `visibility` is
+ /// `hidden`, from the element's own value or an ancestor's. Unlike
+ /// `effectively_invisible` it ignores opacity; `getComputedStyle()`
+ /// reports it.
+ pub visibility_hidden_computed: bool,
/// A CSS image supplied by `content: url(...)` on a replaced element.
/// This is distinct from generated pseudo text: on an `<img>` it becomes
diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rs
index bb62b0fc..0ea7259b 100644
--- a/crates/obscura-render/src/paint.rs
+++ b/crates/obscura-render/src/paint.rs
@@ -1344,6 +1344,40 @@ impl PreparedRender {
}
/// Whether hit testing must ignore this element's generated box.
+ /// CSSOM View `checkVisibility()` over the retained cascade. An element
+ /// without a style, with `display: contents`, or under a `display: none`
+ /// flattened-tree ancestor has no box. `content-visibility: hidden` is
+ /// not implemented by the renderer, which paints that content, so it is
+ /// not consulted here either.
+ pub fn check_visibility(
+ &self,
+ tree: &DomTree,
+ id: obscura_dom::tree::NodeId,
+ check_opacity: bool,
+ check_visibility_css: bool,
+ ) -> bool {
+ let Some(style) = self.layout.styles.get(&id) else {
+ return false;
+ };
+ if style.display_contents || (check_visibility_css && style.visibility_hidden_computed) {
+ return false;
+ }
+ let document = tree.document();
+ let mut current = Some(id);
+ while let Some(node) = current.filter(|&node| node != document) {
+ let Some(style) = self.layout.styles.get(&node) else {
+ return false;
+ };
+ if style.display == crate::Display::None
+ || (check_opacity && style.opacity.is_some_and(|value| value <= 0.0))
+ {
+ return false;
+ }
+ current = crate::dom::rendered_parent(tree, node);
+ }
+ true
+ }
+
pub fn pointer_events_none(&self, id: obscura_dom::tree::NodeId) -> bool {
self.layout
.styles
@@ -1554,7 +1588,7 @@ impl PreparedRender {
);
out.insert(
"visibility",
- if style.visibility_hidden.unwrap_or(false) {
+ if style.visibility_hidden_computed {
"hidden"
} else {
"visible"
@@ -13174,6 +13208,57 @@ mod tests {
assert_eq!(prepared.computed_style(id).unwrap()["outline-width"], "0px");
}
+ #[test]
+ fn computed_visibility_reports_inherited_value() {
+ let tree = parse_html(
+ r#"<html><head><style>.h{visibility:hidden}</style></head><body>
+ <div class="h"><span id="inherited">a</span>
+ <span id="restored" style="visibility:visible">b</span></div>
+ <span id="plain">c</span></body></html>"#,
+ );
+ let mut resources = RenderResourceCache::default();
+ let prepared = prepare_dom(&tree, (80.0, 50.0), None, &mut resources).unwrap();
+ let visibility = |id| {
+ prepared
+ .computed_style(tree.get_element_by_id(id).unwrap())
+ .unwrap()["visibility"]
+ .clone()
+ };
+ assert_eq!(visibility("inherited"), "hidden");
+ assert_eq!(visibility("restored"), "visible");
+ assert_eq!(visibility("plain"), "visible");
+ }
+
+ #[test]
+ fn check_visibility_uses_ancestor_display_opacity_and_computed_visibility() {
+ let tree = parse_html(
+ r#"<html><head><style>.n{display:none}.h{visibility:hidden}.o{opacity:0}
+ .c{display:contents}</style></head><body>
+ <div class="n"><span id="under-none">a</span></div>
+ <div class="h"><span id="under-hidden">b</span></div>
+ <div class="o"><span id="under-transparent">c</span></div>
+ <span id="contents" class="c">d</span>
+ <span id="plain">e</span></body></html>"#,
+ );
+ let mut resources = RenderResourceCache::default();
+ let prepared = prepare_dom(&tree, (80.0, 50.0), None, &mut resources).unwrap();
+ let check = |id, opacity, visibility| {
+ prepared.check_visibility(
+ &tree,
+ tree.get_element_by_id(id).unwrap(),
+ opacity,
+ visibility,
+ )
+ };
+ assert!(!check("under-none", false, false));
+ assert!(check("under-hidden", false, false));
+ assert!(!check("under-hidden", false, true));
+ assert!(check("under-transparent", false, false));
+ assert!(!check("under-transparent", true, false));
+ assert!(!check("contents", false, false));
+ assert!(check("plain", true, true));
+ }
+
#[test]
fn direct_pure_text_webkit_clamp_matches_line_geometry_and_computed_values() {
let tree = parse_html(