Skip to content

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

wip

Gregor Žuniče9824060bd1f
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 7cbb3c3a0..91da96ff3 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -96,7 +96,7 @@ class BrowserContextConfig(BaseModel):
highlight_elements: True
Highlight elements in the DOM on the screen
- viewport_expansion: 500
+ viewport_expansion: 0
Viewport expansion in pixels. This amount will increase the number of elements which are included in the state what the LLM will see. If set to -1, all elements will be included (this leads to high token usage). If set to 0, only the elements which are visible in the viewport will be included.
allowed_domains: None
@@ -145,7 +145,7 @@ class BrowserContextConfig(BaseModel):
)
highlight_elements: bool = True
- viewport_expansion: int = 500
+ viewport_expansion: int = 0
allowed_domains: list[str] | None = None
include_dynamic_attributes: bool = True
diff --git a/browser_use/dom/buildDomTree.js b/browser_use/dom/buildDomTree.js
index 2874ca21d..b808e6dab 100644
--- a/browser_use/dom/buildDomTree.js
+++ b/browser_use/dom/buildDomTree.js
@@ -462,57 +462,135 @@
return false;
}
+ // Define interactive cursors
+ const interactiveCursors = new Set([
+ 'pointer', // Link/clickable elements
+ 'move', // Movable elements
+ 'text', // Text selection
+ 'grab', // Grabbable elements
+ 'grabbing', // Currently grabbing
+ 'cell', // Table cell selection
+ 'copy', // Copy operation
+ 'alias', // Alias creation
+ 'all-scroll', // Scrollable content
+ 'col-resize', // Column resize
+ 'context-menu', // Context menu available
+ 'crosshair', // Precise selection
+ 'e-resize', // East resize
+ 'ew-resize', // East-west resize
+ 'help', // Help available
+ 'n-resize', // North resize
+ 'ne-resize', // Northeast resize
+ 'nesw-resize', // Northeast-southwest resize
+ 'ns-resize', // North-south resize
+ 'nw-resize', // Northwest resize
+ 'nwse-resize', // Northwest-southeast resize
+ 'row-resize', // Row resize
+ 's-resize', // South resize
+ 'se-resize', // Southeast resize
+ 'sw-resize', // Southwest resize
+ 'vertical-text', // Vertical text selection
+ 'w-resize', // West resize
+ 'zoom-in', // Zoom in
+ 'zoom-out' // Zoom out
+ ]);
+
+ // Define non-interactive cursors
+ const nonInteractiveCursors = new Set([
+ 'not-allowed', // Action not allowed
+ 'no-drop', // Drop not allowed
+ 'wait', // Processing
+ 'progress', // In progress
+ 'initial', // Initial value
+ 'inherit' // Inherited value
+ //? Let's just include all potentially clickable elements that are not specifically blocked
+ // 'none', // No cursor
+ // 'default', // Default cursor
+ // 'auto', // Browser default
+ ]);
+
function doesElementHaveInteractivePointer(element) {
if (element.tagName.toLowerCase() === "html") return false;
- const style = window.getComputedStyle(element);
-
- let interactiveCursors = ["pointer", "move", "text", "grab", "cell"];
+ const style = getCachedComputedStyle(element);
- if (interactiveCursors.includes(style.cursor)) return true;
+ if (interactiveCursors.has(style.cursor)) return true;
return false;
}
let isInteractiveCursor = doesElementHaveInteractivePointer(element);
+ // Genius fix for almost all interactive elements
if (isInteractiveCursor) {
return true;
}
- // Special handling for cookie banner elements
- const isCookieBannerElement =
- (typeof element.closest === 'function') && (
- element.closest('[id*="onetrust"]') ||
- element.closest('[class*="onetrust"]') ||
- element.closest('[data-nosnippet="true"]') ||
- element.closest('[aria-label*="cookie"]')
- );
+ const interactiveElements = new Set([
+ "a", // Links
+ "button", // Buttons
+ "input", // All input types (text, checkbox, radio, etc.)
+ "select", // Dropdown menus
+ "textarea", // Text areas
+ "details", // Expandable details
+ "summary", // Summary element (clickable part of details)
+ "label", // Form labels (often clickable)
+ "option", // Select options
+ "optgroup", // Option groups
+ "fieldset", // Form fieldsets (can be interactive with legend)
+ "legend", // Fieldset legends
+ ]);
- if (isCookieBannerElement) {
- // Check if it's a button or interactive element within the banner
- if (
- element.tagName.toLowerCase() === 'button' ||
- element.getAttribute('role') === 'button' ||
- element.onclick ||
- element.getAttribute('onclick') ||
- (element.classList && (
- element.classList.contains('ot-sdk-button') ||
- element.classList.contains('accept-button') ||
- element.classList.contains('reject-button')
- )) ||
- element.getAttribute('aria-label')?.toLowerCase().includes('accept') ||
- element.getAttribute('aria-label')?.toLowerCase().includes('reject')
- ) {
- return true;
+ // Define explicit disable attributes and properties
+ const explicitDisableTags = new Set([
+ 'disabled', // Standard disabled attribute
+ // 'aria-disabled', // ARIA disabled state
+ 'readonly', // Read-only state
+ // 'aria-readonly', // ARIA read-only state
+ // 'aria-hidden', // Hidden from accessibility
+ // 'hidden', // Hidden attribute
+ // 'inert', // Inert attribute
+ // 'aria-inert', // ARIA inert state
+ // 'tabindex="-1"', // Removed from tab order
+ // 'aria-hidden="true"' // Hidden from screen readers
+ ]);
+
+ // handle inputs, select, checkbox, radio, textarea, button and make sure they are not cursor style disabled/not-allowed
+ if (interactiveElements.has(element.tagName.toLowerCase())) {
+ const style = getCachedComputedStyle(element);
+
+ // Check for non-interactive cursor
+ if (nonInteractiveCursors.has(style.cursor)) {
+ return false;
}
+
+ // Check for explicit disable attributes
+ for (const disableTag of explicitDisableTags) {
+ if (element.hasAttribute(disableTag) ||
+ element.getAttribute(disableTag) === 'true' ||
+ element.getAttribute(disableTag) === '') {
+ return false;
+ }
+ }
+
+ // Check for disabled property on form elements
+ if (element.disabled) {
+ return false;
+ }
+
+ // Check for readonly property on form elements
+ if (element.readOnly) {
+ return false;
+ }
+
+ // Check for inert property
+ if (element.inert) {
+ return false;
+ }
+
+ return true;
}
- // Base interactive elements and roles
- const interactiveElements = new Set([
- "a", "button", "details", "embed", "input", "menu", "menuitem",
- "object", "select", "textarea", "canvas", "summary", "dialog",
- "banner"
- ]);
+ return false
const interactiveRoles = new Set(['button-icon', 'dialog', 'button-text-icon-only', 'treeitem', 'alert', 'grid', 'progressbar', 'radio', 'checkbox', 'menuitem', 'option', 'switch', 'dropdown', 'scrollbar', 'combobox', 'a-button-text', 'button', 'region', 'textbox', 'tabpanel', 'tab', 'click', 'button-text', 'spinbutton', 'a-button-inner', 'link', 'menu', 'slider', 'listbox', 'a-dropdown-button', 'button-icon-only', 'searchbox', 'menuitemradio', 'tooltip', 'tree', 'menuitemcheckbox']);
@@ -659,7 +737,8 @@
hasClickHandler ||
hasClickListeners ||
isDraggable ||
- isContentEditable
+ isContentEditable ||
+ false
);
}
@@ -669,16 +748,21 @@
function isTopElement(element) {
const rect = getCachedBoundingRect(element);
- // If element is not in viewport, consider it top
- const isInViewport = (
- rect.left < window.innerWidth &&
- rect.right > 0 &&
- rect.top < window.innerHeight &&
- rect.bottom > 0
- );
-
- if (!isInViewport) {
- return true;
+ if (viewportExpansion <= 0) {
+ if (rect.bottom < 0 ||
+ rect.top > window.innerHeight ||
+ rect.right < 0 ||
+ rect.left > window.innerWidth) {
+ return false;
+ }
+ } else {
+ // For positive viewportExpansion, only expand in Y direction
+ if (rect.bottom < -viewportExpansion ||
+ rect.top > window.innerHeight + viewportExpansion ||
+ rect.right < 0 ||
+ rect.left > window.innerWidth) {
+ return false;
+ }
}
// Find the correct document context and root element
diff --git a/browser_use/dom/tests/extraction_test.py b/browser_use/dom/tests/extraction_test.py
index 4a5dda168..01aa68c51 100644
--- a/browser_use/dom/tests/extraction_test.py
+++ b/browser_use/dom/tests/extraction_test.py
@@ -102,7 +102,9 @@ async def test_focus_vs_all_elements():
context = BrowserContext(browser=browser, config=config) # noqa: F821
websites = [
+ # 'https://www.concur.com/?&cookie_preferences=cpra',
'https://immobilienscout24.de',
+ 'https://docs.google.com/spreadsheets/d/1INaIcfpYXlMRWO__de61SHFCaqt1lfHlcvtXZPItlpI/edit',
'https://www.zeiss.com/career/en/job-search.html?page=1',
'https://www.mlb.com/yankees/stats/',
'https://www.amazon.com/s?k=laptop&s=review-rank&crid=1RZCEJ289EUSI&qid=1740202453&sprefix=laptop%2Caps%2C166&ref=sr_st_review-rank&ds=v1%3A4EnYKXVQA7DIE41qCvRZoNB4qN92Jlztd3BPsTFXmxU',
@@ -132,13 +134,15 @@ async def test_focus_vs_all_elements():
# First get all elements
print('\nGetting all elements:')
all_elements_state = await time_execution_sync('get_all_elements')(dom_service.get_clickable_elements)(
- highlight_elements=True, viewport_expansion=100
+ highlight_elements=True, viewport_expansion=1000
)
selector_map = all_elements_state.selector_map
total_elements = len(selector_map.keys())
print(f'Total number of elements: {total_elements}')
+ print(all_elements_state.element_tree.clickable_elements_to_string())
+
answer = input('Press Enter to clear highlights and continue...')
if answer == 'q':
break