Skip to content

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

dont change agent focus outside?

mertunsalld7600603a2ed
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 261535f6f..08f767155 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -942,12 +942,9 @@ class BrowserSession(BaseModel):
# Switch to the target
assert event.target_id is not None, 'target_id must be set at this point'
- # Ensure session exists
+ # Ensure session exists and update agent focus (only for page/tab targets)
cdp_session = await self.get_or_create_cdp_session(target_id=event.target_id, focus=True)
- # Update agent focus to this target
- self.agent_focus_target_id = event.target_id
-
# Visually switch to the tab in the browser
# The Force Background Tab extension prevents Chrome from auto-switching when links create new tabs,
# but we still want the agent to be able to explicitly switch tabs when needed
@@ -1027,12 +1024,10 @@ 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:]}')
else:
raise RuntimeError('AgentFocusChangedEvent received with no target_id for newly focused tab')
@@ -1143,6 +1138,26 @@ class BrowserSession(BaseModel):
return targets
+ def get_focused_target(self) -> 'Target | None':
+ """Get the target that currently has agent focus.
+
+ Returns:
+ Target object if agent has focus, None otherwise.
+ """
+ if not self.session_manager:
+ return None
+ return self.session_manager.get_focused_target()
+
+ def get_page_targets(self) -> list['Target']:
+ """Get all page/tab targets (excludes iframes, workers, etc.).
+
+ Returns:
+ List of Target objects for all page/tab targets.
+ """
+ if not self.session_manager:
+ return []
+ return self.session_manager.get_all_page_targets()
+
async def close_page(self, page: 'Union[Page, str]') -> None:
"""Close a page by Page object or target ID."""
from cdp_use.cdp.target.commands import CloseTargetParameters