Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

fixes for viewportExpansion=-1 mode to force-include all elements

Nick Sweeting457e97842db2
diff --git a/browser_use/dom/buildDomTree.js b/browser_use/dom/buildDomTree.js
index a61bfa0c0..932b97f37 100644
--- a/browser_use/dom/buildDomTree.js
+++ b/browser_use/dom/buildDomTree.js
@@ -523,6 +523,26 @@
*/
function isTextNodeVisible(textNode) {
try {
+ // Special case: when viewportExpansion is -1, consider all text nodes as visible
+ if (viewportExpansion === -1) {
+ // Still check parent visibility for basic filtering
+ const parentElement = textNode.parentElement;
+ if (!parentElement) return false;
+
+ try {
+ return parentElement.checkVisibility({
+ checkOpacity: true,
+ checkVisibilityCSS: true,
+ });
+ } catch (e) {
+ // Fallback if checkVisibility is not supported
+ const style = window.getComputedStyle(parentElement);
+ return style.display !== 'none' &&
+ style.visibility !== 'hidden' &&
+ style.opacity !== '0';
+ }
+ }
+
const range = document.createRange();
range.selectNodeContents(textNode);
const rects = range.getClientRects(); // Use getClientRects for Range
@@ -545,7 +565,7 @@
rect.top > window.innerHeight + viewportExpansion ||
rect.right < -viewportExpansion ||
rect.left > window.innerWidth + viewportExpansion
- ) || viewportExpansion === -1) {
+ )) {
isAnyRectInViewport = true;
break; // Found a visible rect in viewport, no need to check others
}
@@ -834,6 +854,11 @@
* Checks if an element is the topmost element at its position.
*/
function isTopElement(element) {
+ // Special case: when viewportExpansion is -1, consider all elements as "top" elements
+ if (viewportExpansion === -1) {
+ return true;
+ }
+
const rects = getCachedClientRects(element); // Replace element.getClientRects()
if (!rects || rects.length === 0) {
@@ -843,12 +868,12 @@
let isAnyRectInViewport = false;
for (const rect of rects) {
// Use the same logic as isInExpandedViewport check
- if (viewportExpansion === -1 || (rect.width > 0 && rect.height > 0 && !( // Only check non-empty rects
+ if (rect.width > 0 && rect.height > 0 && !( // Only check non-empty rects
rect.bottom < -viewportExpansion ||
rect.top > window.innerHeight + viewportExpansion ||
rect.right < -viewportExpansion ||
rect.left > window.innerWidth + viewportExpansion
- ))) {
+ )) {
isAnyRectInViewport = true;
break;
}
@@ -1098,7 +1123,10 @@
if (shouldHighlight) {
// Check viewport status before assigning index and highlighting
nodeData.isInViewport = isInExpandedViewport(node, viewportExpansion);
- if (nodeData.isInViewport) {
+
+ // When viewportExpansion is -1, all interactive elements should get a highlight index
+ // regardless of viewport status
+ if (nodeData.isInViewport || viewportExpansion === -1) {
nodeData.highlightIndex = highlightIndex++;
if (doHighlightElements) {