Skip to content

The headless browser for AI agents and web scraping

fix(dom): clear removed focus and scroll nested containers

SGavrlc714042f595d
diff --git a/crates/obscura-cdp/src/domains/dom.rs b/crates/obscura-cdp/src/domains/dom.rs
index 7caf0db9..138f777b 100644
--- a/crates/obscura-cdp/src/domains/dom.rs
+++ b/crates/obscura-cdp/src/domains/dom.rs
@@ -234,12 +234,12 @@ pub async fn handle(
"scrollIntoViewIfNeeded" => {
let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
let node_id = resolve_node_id(page, params)?;
- // Obscura has no layout viewport to move, but the JS shim records
- // this element for the hit testing used by subsequent input events.
+ // Share the DOM shim's nested-scrollport handling. Fully visible
+ // boxes stay put; clipped boxes are centered only where needed.
let code = format!(
"(function() {{ var el = globalThis._wrap && globalThis._wrap({0}); \
- if (!el || typeof el.scrollIntoView !== 'function') return false; \
- el.scrollIntoView(); return true; }})()",
+ if (!el || typeof el.scrollIntoViewIfNeeded !== 'function') return false; \
+ el.scrollIntoViewIfNeeded(); return true; }})()",
node_id
);
let did_scroll = page.evaluate(&code).as_bool().unwrap_or(false);
@@ -763,6 +763,24 @@ mod tests {
}
}
+ #[tokio::test(flavor = "current_thread")]
+ #[cfg(feature = "render")]
+ async fn scroll_into_view_if_needed_preserves_visible_positions() {
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let session = Some(format!("{page_id}-session"));
+ ctx.sessions.insert(session.clone().unwrap(), page_id);
+ crate::domains::page::handle("navigate", &json!({
+ "url": "data:text/html,<body style='margin:0;height:1800px'><div style='height:200px'></div><button id=target style='height:40px'>Go</button></body>",
+ "waitUntil": "load"
+ }), &mut ctx, &session).await.unwrap();
+ let node = handle("querySelector", &json!({"selector":"#target"}), &mut ctx, &session).await.unwrap();
+ handle("scrollIntoViewIfNeeded", &json!({"nodeId":node["nodeId"]}), &mut ctx, &session).await.unwrap();
+ let position = ctx.get_session_page_mut(&session).unwrap()
+ .evaluate("[scrollY, document.getElementById('target').getBoundingClientRect().top]");
+ assert_eq!(position, json!([0, 200]));
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn scroll_into_view_if_needed_requires_a_node_identifier() {
let mut ctx = CdpContext::new();
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 674a7182..d2f80d37 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -154,6 +154,10 @@ const _dom = (cmd, a1, a2) => {
// not make JS believe a move happened.
if (result === "true" && _DOM_TREE_MUTATION_COMMANDS.has(cmd)) {
_treeMutationEpoch++;
+ // HTML removal steps reset the focused area to the viewport without
+ // dispatching blur/change events. Cover native replacement paths too.
+ const focused = globalThis.__obscura_focused;
+ if (focused && !focused.isConnected) globalThis.__obscura_focused = null;
}
return result;
};
@@ -5255,23 +5259,22 @@ class Element extends Node {
get ariaSelected() { return this.getAttribute('aria-selected'); }
set ariaSelected(v) { if (v == null) this.removeAttribute('aria-selected'); else this.setAttribute('aria-selected', String(v)); }
scrollIntoView(arg) {
- globalThis.__obscura_click_target = this;
- const rect = this.getBoundingClientRect();
- // A viewport-fixed subtree is already expressed in the viewport's
- // coordinate space and cannot be brought closer by moving the document.
- if (rect.__obscuraViewportFixed) return;
-
let block = "start", inline = "nearest";
if (arg === false) block = "end";
else if (arg && typeof arg === "object") {
if (["start", "center", "end", "nearest"].includes(arg.block)) block = arg.block;
if (["start", "center", "end", "nearest"].includes(arg.inline)) inline = arg.inline;
}
- const currentX = globalThis.scrollX || 0;
- const currentY = globalThis.scrollY || 0;
- const vw = globalThis.innerWidth || 1280;
- const vh = globalThis.innerHeight || 720;
+ this._scrollIntoView(block, inline, false, arg && arg.behavior);
+ }
+ scrollIntoViewIfNeeded(centerIfNeeded = true) {
+ const alignment = centerIfNeeded ? "center" : "nearest";
+ this._scrollIntoView(alignment, alignment, true);
+ }
+ _scrollIntoView(block, inline, onlyIfNeeded, behavior) {
+ globalThis.__obscura_click_target = this;
const align = (mode, start, end, size, viewportSize, current) => {
+ if (onlyIfNeeded && start >= 0 && end <= viewportSize) return current;
if (mode === "start") return current + start;
if (mode === "center") return current + start - (viewportSize - size) / 2;
if (mode === "end") return current + end - viewportSize;
@@ -5280,13 +5283,41 @@ class Element extends Node {
if ((start >= 0 && end <= viewportSize) || (start < 0 && end > viewportSize)) {
return current;
}
- if (start < 0) return current + start;
- if (end > viewportSize) return current + end - viewportSize;
+ if (start < 0) return current + (size <= viewportSize ? start : end - viewportSize);
+ if (end > viewportSize) return current + (size <= viewportSize ? end - viewportSize : start);
return current;
};
+ // Use the renderer's retained scroll ranges, not overflow guesses. A
+ // clipped/non-scrolling box has zero range even when descendants overflow.
+ const viewportFixed = this.getBoundingClientRect().__obscuraViewportFixed;
+ for (let ancestor = this.parentElement;
+ typeof __obscuraCore.ops.op_element_scroll_metrics === 'function' && ancestor && !ancestor._isViewportRoot();
+ ancestor = ancestor.parentElement) {
+ const metrics = ancestor._renderElementScrollMetrics();
+ if (metrics && (metrics.maxX > 0 || metrics.maxY > 0)) {
+ const rect = this.getBoundingClientRect();
+ const port = ancestor.getBoundingClientRect();
+ const x = port.left + ancestor.clientLeft;
+ const y = port.top + ancestor.clientTop;
+ ancestor.scrollTo({
+ left: align(inline, rect.left - x, rect.right - x, rect.width, metrics.clientWidth, metrics.x),
+ top: align(block, rect.top - y, rect.bottom - y, rect.height, metrics.clientHeight, metrics.y),
+ behavior,
+ });
+ }
+ // A fixed scrollport can scroll its contents, but moving ancestors
+ // outside its fixed containing block cannot bring the target into view.
+ if (viewportFixed && globalThis.getComputedStyle(ancestor).position === 'fixed') break;
+ }
+ const rect = this.getBoundingClientRect();
+ if (rect.__obscuraViewportFixed) return;
+ const currentX = globalThis.scrollX || 0;
+ const currentY = globalThis.scrollY || 0;
+ const vw = globalThis.innerWidth || 1280;
+ const vh = globalThis.innerHeight || 720;
const left = align(inline, rect.left, rect.right, rect.width, vw, currentX);
const top = align(block, rect.top, rect.bottom, rect.height, vh, currentY);
- globalThis.scrollTo({ left, top, behavior: arg && arg.behavior });
+ globalThis.scrollTo({ left, top, behavior });
}
// scrollTo/scrollBy/scroll accept either (x, y) or a ScrollToOptions object.
// The setters fire a scroll event of their own, so suppress the per-axis ones
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 9de9b8e5..2463246c 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -13672,6 +13672,75 @@ mod tests {
);
}
+ #[cfg(feature = "render")]
+ #[tokio::test(flavor = "current_thread")]
+ async fn scroll_into_view_moves_nested_scrollports_before_the_viewport() {
+ let dom = parse_html(
+ r#"<html style="margin:0"><body style="margin:0;height:1800px">
+ <div id="scroller" style="margin-top:200px;height:200px;overflow:auto">
+ <div style="height:600px"></div>
+ <div id="target" style="height:40px"></div>
+ <div style="height:600px"></div>
+ </div>
+ </body></html>"#,
+ );
+ let mut rt = ObscuraJsRuntime::new();
+ rt.set_dom(dom);
+ rt.set_viewport(800.0, 600.0);
+ rt.run_page_init();
+ let result = rt.evaluate(r#"
+ const scroller = document.getElementById('scroller');
+ const target = document.getElementById('target');
+ const results = [];
+ for (const block of ['nearest', 'center', 'start', 'end']) {
+ scrollTo(0, 0);
+ scroller.scrollTop = 0;
+ target.scrollIntoView({block});
+ results.push([scroller.scrollTop, scrollY, target.getBoundingClientRect().top]);
+ }
+ scrollTo(0, 0);
+ target.scrollIntoView({block: 'nearest'});
+ results.push([scroller.scrollTop, scrollY, target.getBoundingClientRect().top]);
+ return results;
+ "#).unwrap();
+ assert_eq!(result, serde_json::json!([
+ [440, 0, 360], [520, 0, 280], [600, 200, 0],
+ [440, 0, 360], [440, 0, 360],
+ ]));
+ }
+
+ #[test]
+ fn removing_a_focused_subtree_clears_focus_without_firing_blur() {
+ let mut rt = setup_runtime("<main id=parent></main>");
+ let result = rt.evaluate(r#"
+ const parent = document.getElementById('parent');
+ const rows = [];
+ for (const remove of [
+ host => host.remove(),
+ host => parent.removeChild(host),
+ host => parent.replaceChild(document.createElement('div'), host),
+ host => { parent.innerHTML = ''; },
+ host => { parent.textContent = ''; },
+ host => parent.replaceChildren(),
+ host => host.replaceWith(document.createElement('div')),
+ ]) {
+ parent.innerHTML = '<section><button>Apply</button></section>';
+ const host = parent.firstChild, button = host.firstChild;
+ let blurred = 0;
+ button.addEventListener('blur', () => blurred++);
+ button.addEventListener('focusout', () => blurred++);
+ button.focus();
+ const focused = document.activeElement === button;
+ remove(host);
+ // Reinsert without reading activeElement while disconnected.
+ parent.appendChild(host);
+ rows.push([focused, document.activeElement === document.body, blurred]);
+ }
+ return rows;
+ "#).unwrap();
+ assert_eq!(result, serde_json::json!(vec![serde_json::json!([true,true,0]); 7]));
+ }
+
#[cfg(feature = "render")]
#[tokio::test(flavor = "current_thread")]
async fn scroll_into_view_emits_events_only_when_the_root_moves() {
diff --git a/render-repros/checks.json b/render-repros/checks.json
index b279c529..66609580 100644
--- a/render-repros/checks.json
+++ b/render-repros/checks.json
@@ -363,6 +363,10 @@
{"name": "cell vertical-align overrides the row default", "color": "#2b8a3e", "x": 200, "y": 240, "width": 20, "height": 20},
{"name": "UA cell padding is one pixel on every edge", "color": "#1971c2", "x": 2, "y": 332, "width": 12, "height": 12}
],
+ "scroll-into-view": [
+ {"name": "nested scrollport brings the target inside its padding box", "color": "#087f5b", "x": 25, "y": 365, "width": 100, "height": 40},
+ {"name": "fixed scrollport scrolls both axes without moving the document", "color": "#7048e8", "x": 405, "y": 365, "width": 100, "height": 40}
+ ],
"text-align-flex-items": [
{"name": "text alignment does not shrink a flex item", "color": "#087f5b", "x": 20, "y": 20, "width": 360, "height": 80},
{"name": "inherited text alignment centers inline content", "color": "#c2255c", "x": 150, "y": 100, "width": 100, "height": 20}
diff --git a/render-repros/scroll-into-view.html b/render-repros/scroll-into-view.html
new file mode 100644
index 00000000..d8706990
--- /dev/null
+++ b/render-repros/scroll-into-view.html
@@ -0,0 +1,21 @@
+<!doctype html>
+<meta charset="utf-8">
+<style>
+ html, body { margin:0; }
+ body { height:1800px; }
+ .port { position:absolute;left:20px;top:200px;width:200px;height:200px;
+ overflow:auto;border:5px solid #222;background:#ddd; }
+ #fixed { position:fixed;left:300px; }
+ .before, .after { height:600px; }
+ .target { width:100px;height:40px;background:#087f5b; }
+ #fixed .target { margin-left:600px;background:#7048e8; }
+</style>
+<div class="port"><div class="before"></div><div id="normal-target" class="target"></div><div class="after"></div></div>
+<div id="fixed" class="port"><div class="before"></div><div id="fixed-target" class="target"></div><div class="after"></div></div>
+<script>
+ addEventListener('load', () => {
+ for (const id of ['normal-target', 'fixed-target']) {
+ document.getElementById(id).scrollIntoView({block:'nearest', inline:'nearest'});
+ }
+ });
+</script>