Skip to content

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

fix(browser): prevent remove_highlights() from blocking screenshot handler on slow pages

Saurav Pandaf8c729d468d3
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 0e0f62bc0..716eec07e 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -2531,41 +2531,42 @@ class BrowserSession(BaseModel):
return
try:
- # Get cached session
- cdp_session = await self.get_or_create_cdp_session()
-
- # Remove highlights via JavaScript - be thorough
- script = """
- (function() {
- // Remove all browser-use highlight elements
- const highlights = document.querySelectorAll('[data-browser-use-highlight]');
- console.log('Removing', highlights.length, 'browser-use highlight elements');
- highlights.forEach(el => el.remove());
-
- // Also remove by ID in case selector missed anything
- const highlightContainer = document.getElementById('browser-use-debug-highlights');
- if (highlightContainer) {
- console.log('Removing highlight container by ID');
- highlightContainer.remove();
- }
-
- // Final cleanup - remove any orphaned tooltips
- const orphanedTooltips = document.querySelectorAll('[data-browser-use-highlight="tooltip"]');
- orphanedTooltips.forEach(el => el.remove());
-
- return { removed: highlights.length };
- })();
- """
- result = await cdp_session.cdp_client.send.Runtime.evaluate(
- params={'expression': script, 'returnByValue': True}, session_id=cdp_session.session_id
- )
+ async with asyncio.timeout(3.0):
+ # Get cached session
+ cdp_session = await self.get_or_create_cdp_session()
+
+ # Remove highlights via JavaScript - be thorough
+ script = """
+ (function() {
+ // Remove all browser-use highlight elements
+ const highlights = document.querySelectorAll('[data-browser-use-highlight]');
+ console.log('Removing', highlights.length, 'browser-use highlight elements');
+ highlights.forEach(el => el.remove());
+
+ // Also remove by ID in case selector missed anything
+ const highlightContainer = document.getElementById('browser-use-debug-highlights');
+ if (highlightContainer) {
+ console.log('Removing highlight container by ID');
+ highlightContainer.remove();
+ }
+
+ // Final cleanup - remove any orphaned tooltips
+ const orphanedTooltips = document.querySelectorAll('[data-browser-use-highlight="tooltip"]');
+ orphanedTooltips.forEach(el => el.remove());
+
+ return { removed: highlights.length };
+ })();
+ """
+ result = await cdp_session.cdp_client.send.Runtime.evaluate(
+ params={'expression': script, 'returnByValue': True}, session_id=cdp_session.session_id
+ )
- # Log the result for debugging
- if result and 'result' in result and 'value' in result['result']:
- removed_count = result['result']['value'].get('removed', 0)
- self.logger.debug(f'Successfully removed {removed_count} highlight elements')
- else:
- self.logger.debug('Highlight removal completed')
+ # Log the result for debugging
+ if result and 'result' in result and 'value' in result['result']:
+ removed_count = result['result']['value'].get('removed', 0)
+ self.logger.debug(f'Successfully removed {removed_count} highlight elements')
+ else:
+ self.logger.debug('Highlight removal completed')
except Exception as e:
self.logger.warning(f'Failed to remove highlights: {e}')
diff --git a/browser_use/browser/watchdogs/screenshot_watchdog.py b/browser_use/browser/watchdogs/screenshot_watchdog.py
index 91f18bff5..b05c6864f 100644
--- a/browser_use/browser/watchdogs/screenshot_watchdog.py
+++ b/browser_use/browser/watchdogs/screenshot_watchdog.py
@@ -78,8 +78,10 @@ class ScreenshotWatchdog(BaseWatchdog):
self.logger.error(f'[ScreenshotWatchdog] Screenshot failed: {e}')
raise
finally:
- # Try to remove highlights even on failure
+ # Try to remove highlights even on failure.
+ # Use BaseException to also catch CancelledError so task cancellation
+ # doesn't propagate out of the finally block and trigger a spurious timeout.
try:
await self.browser_session.remove_highlights()
- except Exception:
+ except BaseException:
pass