Skip to content

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

Merge branch 'main' into mert/fix_screenshot_bug

Mert Unsalcb21a1b70ea2
diff --cc browser_use/browser/session.py
index 08f767155,6af3d4528..da33e2094
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@@ -1024,11 -1027,27 +1024,25 @@@ class BrowserSession(BaseModel)
self._cached_selector_map.clear()
self.logger.debug('🔄 Cached browser state cleared')
- # Update agent focus if a specific target_id is provided
+ # Update agent focus if a specific target_id is provided (only for page/tab targets)
if event.target_id:
- # Ensure session exists for this target
+ # Ensure session exists and update agent focus (validates target_type internally)
await self.get_or_create_cdp_session(target_id=event.target_id, focus=True)
- # Update agent focus target
- self.agent_focus_target_id = event.target_id
self.logger.debug(f'🔄 Updated agent focus to tab target_id=...{event.target_id[-4:]}')
+
+ # Apply viewport settings to the newly focused tab
+ if self.browser_profile.viewport and not self.browser_profile.no_viewport:
+ try:
+ viewport_width = self.browser_profile.viewport.width
+ viewport_height = self.browser_profile.viewport.height
+ device_scale_factor = self.browser_profile.device_scale_factor or 1.0
+
+ # Use the helper method with the current tab's target_id
+ await self._cdp_set_viewport(viewport_width, viewport_height, device_scale_factor, target_id=event.target_id)
+
+ self.logger.debug(f'Applied viewport {viewport_width}x{viewport_height} to tab {event.target_id[-8:]}')
+ except Exception as e:
+ self.logger.warning(f'Failed to set viewport for tab {event.target_id[-8:]}: {e}')
else:
raise RuntimeError('AgentFocusChangedEvent received with no target_id for newly focused tab')