Skip to content

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

fix search_google nav

Nick Sweetingd1c9ddd9feca
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.py
index 3f3540b67..d7ab84d96 100644
--- a/browser_use/browser/events.py
+++ b/browser_use/browser/events.py
@@ -97,7 +97,7 @@ class ClickElementEvent(ElementSelectedEvent[None]):
button: Literal['left', 'right', 'middle'] = 'left'
new_tab: bool = Field(
default=False,
- description='Set True to open any link clicked in a new tab in the background, can use switch_tab(page_id=-1) after to focus it',
+ description='Set True to open any link clicked in a new tab in the background, can use switch_tab(page_id=0) after to focus it',
)
# click_count: int = 1 # TODO
# expect_download: bool = False # moved to downloads_watchdog.py
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 11fb03135..ff4fe9c22 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -440,9 +440,9 @@ class BrowserSession(BaseModel):
else:
# Use current tab
target_id = self.agent_focus.target_id
- tab_index = await self.get_tab_index(target_id)
# Activate target (bring to foreground)
+ tab_index = await self.get_tab_index(target_id)
await self.event_bus.dispatch(SwitchTabEvent(tab_index=tab_index))
# Update agent focus to the target
@@ -644,78 +644,69 @@ class BrowserSession(BaseModel):
return self._cdp_client_root
async def get_or_create_cdp_session(
- self, target_id: str | None = None, focus: bool = True, new_socket: bool | None = None, domains: list[str] | None = None
+ self, target_id: str | None = None, focus: bool = True, new_socket: bool | None = None
) -> CDPSession:
- """Get or create a CDP session for a target.
+ """Get or create a CDP session for a target.
- Args:
- target_id: Target ID to get session for. If None, uses current agent focus.
- If 'main', finds any about:blank target to use.
- focus: If True, switches agent focus to this target. If False, just returns session without changing focus.
- new_socket: If True, create a dedicated WebSocket connection. If None (default), creates new socket for new targets only.
- domains: List of CDP domains to enable (e.g., ['Browser', 'Storage']). If None, enables default domains.
+ Args:
+ target_id: Target ID to get session for. If None, uses current agent focus.
+ focus: If True, switches agent focus to this target. If False, just returns session without changing focus.
+ new_socket: If True, create a dedicated WebSocket connection. If None (default), creates new socket for new targets only.
- Returns:
- CDPSession for the specified target.
- """
- assert self.cdp_url is not None, 'CDP URL not set - browser may not be configured or launched yet'
- assert self._cdp_client_root is not None, 'Root CDP client not initialized - browser may not be connected yet'
- assert self.agent_focus is not None, 'CDP session not initialized - browser may not be connected yet'
-
- target_id = target_id or self.agent_focus.target_id
-
- if target_id == 'main' and self.agent_focus.target_id:
- target_id = self.agent_focus.target_id
- elif target_id == 'main' and not self.agent_focus.target_id:
- all_targets = await self._cdp_client_root.send.Target.getTargets()
- spare_bg_target = [
- target
- for target in all_targets.get('targetInfos', [])
- if target.get('type') == 'page' and target.get('url') == 'about:blank'
- ]
- if spare_bg_target:
- target_id = spare_bg_target[0]['targetId']
-
- if target_id is None:
+ Returns:
+ CDPSession for the specified target.
+ """
+ assert self.cdp_url is not None, 'CDP URL not set - browser may not be configured or launched yet'
assert self._cdp_client_root is not None, 'Root CDP client not initialized - browser may not be connected yet'
- result = await self._cdp_client_root.send.Target.createTarget(params={'url': 'about:blank'})
- target_id = result['targetId']
+ assert self.agent_focus is not None, 'CDP session not initialized - browser may not be connected yet'
+
+ # If no target_id specified, use the current target_id
+ if target_id is None:
+ target_id = self.agent_focus.target_id
+
+ # Check if we already have a session for this target in the pool
+ if target_id in self._cdp_session_pool:
+ session = self._cdp_session_pool[target_id]
+ if focus and self.agent_focus.target_id != target_id:
+ self.logger.debug(
+ f'[get_or_create_cdp_session] Switching agent focus from {self.agent_focus.target_id} to {target_id}'
+ )
+ self.agent_focus = session
+ else:
+ self.logger.debug(f'[get_or_create_cdp_session] Reusing existing session for {target_id} (focus={focus})')
+ return session
+
+ # If it's the current focus target, return that session
+ if self.agent_focus.target_id == target_id:
+ self._cdp_session_pool[target_id] = self.agent_focus
+ return self.agent_focus
+
+ # Create new session for this target
+ # Default to True for new sessions (each new target gets its own WebSocket)
+ should_use_new_socket = True if new_socket is None else new_socket
self.logger.debug(
- f"[get_or_create_cdp_session] Created new target {target_id} for 'main' request with domains={domains}"
+ f'[get_or_create_cdp_session] Creating new CDP session for target {target_id} (new_socket={should_use_new_socket})'
)
-
- assert target_id is not None, 'No target_id provided and no about:blank tab or open page found'
-
- if new_socket:
session = await CDPSession.for_target(
- self._cdp_client_root,
- target_id=target_id,
- new_socket=new_socket,
- cdp_url=self.cdp_url,
- domains=domains,
- )
- else:
- session = self._cdp_session_pool.get(target_id)
- if session is None:
- session = await CDPSession.for_target(
self._cdp_client_root,
- target_id=target_id,
- new_socket=True,
- cdp_url=self.cdp_url,
- domains=domains,
- )
- self._cdp_session_pool[target_id] = session
-
- assert session is not None, 'Failed to create CDP session for target_id'
-
- if focus:
- self.agent_focus = session
+ target_id,
+ new_socket=should_use_new_socket,
+ cdp_url=self.cdp_url if should_use_new_socket else None,
+ )
self._cdp_session_pool[target_id] = session
- else:
- if not new_socket:
- self._cdp_session_pool[target_id] = session
- return session
+ # Only change agent focus if requested
+ if focus:
+ self.logger.debug(
+ f'[get_or_create_cdp_session] Switching agent focus from {self.agent_focus.target_id} to {target_id}'
+ )
+ self.agent_focus = session
+ else:
+ self.logger.debug(
+ f'[get_or_create_cdp_session] Created session for {target_id} without changing focus (still on {self.agent_focus.target_id})'
+ )
+
+ return session
@property
def current_target_id(self) -> str | None:
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 4a22e8eac..41fc68902 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -120,8 +120,7 @@ class Controller(Generic[Context]):
elif tab.url == 'about:blank' and tab.title:
# Check if this is our agent's about:blank page with DVD animation
# The title should be "Starting agent XXXX..." where XXXX is the browser_session_label
- expected_title = f'Starting agent {browser_session_label}...'
- if tab.title == expected_title or browser_session_label in tab.title:
+ if browser_session_label in tab.title:
# This is our agent's about:blank page
logger.debug(f'Found agent-owned about:blank tab at index {i} with title: "{tab.title}", reusing it')