Skip to content

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

allow providing chrome_remote_debugging_port in browser config. fix launching user provided chrome browser.

Prenit Wankhede0b21e50ca640
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 82131b9ba..e2a057b94 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -1222,7 +1222,7 @@ class Agent(Generic[Context]):
test_answer = 'paris'
try:
# dont convert this to async! it *should* block any subsequent llm calls from running
- response = self.llm.invoke([HumanMessage(content=test_prompt)]) # noqa: ASYNC
+ response = self.llm.invoke([HumanMessage(content=test_prompt)]) # noqa: RUF006
response_text = str(response.content).lower()
if test_answer in response_text:
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.py
index 38a86b674..b7448e9d6 100644
--- a/browser_use/browser/browser.py
+++ b/browser_use/browser/browser.py
@@ -21,6 +21,8 @@ load_dotenv()
from browser_use.browser.chrome import (
CHROME_ARGS,
+ CHROME_DEBUG_PORT,
+ CHROME_DEBUGGING_ARG,
CHROME_DETERMINISTIC_RENDERING_ARGS,
CHROME_DISABLE_SECURITY_ARGS,
CHROME_DOCKER_ARGS,
@@ -77,6 +79,12 @@ class BrowserConfig(BaseModel):
Path to a Browser instance to use to connect to your normal browser
e.g. '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'
+ chrome_remote_debugging_port: 9222
+ Chrome remote debugging port to use to when browser_binary_path is supplied.
+ This allows running multiple chrome browsers with same browser_binary_path but running on different ports.
+ Also, makes it possible to launch new user provided chrome browser without closing already opened chrome instances,
+ by providing non-default chrome debugging port.
+
keep_alive: False
Keep the browser alive after the agent has finished running
@@ -100,6 +108,7 @@ class BrowserConfig(BaseModel):
browser_binary_path: str | None = Field(
default=None, validation_alias=AliasChoices('browser_instance_path', 'chrome_instance_path')
)
+ chrome_remote_debugging_port: int | None = CHROME_DEBUG_PORT
extra_browser_args: list[str] = Field(default_factory=list)
headless: bool = False
@@ -189,12 +198,16 @@ class Browser:
try:
# Check if browser is already running
async with httpx.AsyncClient() as client:
- response = await client.get('http://localhost:9222/json/version', timeout=2)
+ response = await client.get(
+ f'http://localhost:{self.config.chrome_remote_debugging_port}/json/version', timeout=2
+ )
if response.status_code == 200:
- logger.info('🔌 Reusing existing browser found running on http://localhost:9222')
+ logger.info(
+ f'🔌 Reusing existing browser found running on http://localhost:{self.config.chrome_remote_debugging_port}'
+ )
browser_class = getattr(playwright, self.config.browser_class)
browser = await browser_class.connect_over_cdp(
- endpoint_url='http://localhost:9222',
+ endpoint_url=f'http://localhost:{self.config.chrome_remote_debugging_port}',
timeout=20000, # 20 second timeout for connection
)
return browser
@@ -202,9 +215,9 @@ class Browser:
logger.debug('🌎 No existing Chrome instance found, starting a new one')
# Start a new Chrome instance
- chrome_launch_cmd = [
- self.config.browser_binary_path,
+ chrome_launch_args = [
*{ # remove duplicates (usually preserves the order, but not guaranteed)
+ CHROME_DEBUGGING_ARG % {'chrome_remote_debugging_port': self.config.chrome_remote_debugging_port},
*CHROME_ARGS,
*(CHROME_DOCKER_ARGS if IN_DOCKER else []),
*(CHROME_HEADLESS_ARGS if self.config.headless else []),
@@ -213,20 +226,22 @@ class Browser:
*self.config.extra_browser_args,
},
]
- self._chrome_subprocess = psutil.Process(
- await asyncio.create_subprocess_shell(
- chrome_launch_cmd,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- shell=False,
- ).pid
+ chrome_sub_process = await asyncio.create_subprocess_exec(
+ self.config.browser_binary_path,
+ *chrome_launch_args,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ shell=False,
)
+ self._chrome_subprocess = psutil.Process(chrome_sub_process.pid)
# Attempt to connect again after starting a new instance
for _ in range(10):
try:
async with httpx.AsyncClient() as client:
- response = await client.get('http://localhost:9222/json/version', timeout=2)
+ response = await client.get(
+ f'http://localhost:{self.config.chrome_remote_debugging_port}/json/version', timeout=2
+ )
if response.status_code == 200:
break
except httpx.RequestError:
@@ -237,7 +252,7 @@ class Browser:
try:
browser_class = getattr(playwright, self.config.browser_class)
browser = await browser_class.connect_over_cdp(
- endpoint_url='http://localhost:9222',
+ endpoint_url=f'http://localhost:{self.config.chrome_remote_debugging_port}',
timeout=20000, # 20 second timeout for connection
)
return browser
@@ -259,6 +274,7 @@ class Browser:
offset_x, offset_y = get_window_adjustments()
chrome_args = {
+ CHROME_DEBUGGING_ARG % {'chrome_remote_debugging_port': self.config.chrome_remote_debugging_port},
*CHROME_ARGS,
*(CHROME_DOCKER_ARGS if IN_DOCKER else []),
*(CHROME_HEADLESS_ARGS if self.config.headless else []),
@@ -269,10 +285,11 @@ class Browser:
*self.config.extra_browser_args,
}
- # check if port 9222 is already taken, if so remove the remote-debugging-port arg to prevent conflicts
+ # check if chrome remote debugging port is already taken,
+ # if so remove the remote-debugging-port arg to prevent conflicts
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
- if s.connect_ex(('localhost', 9222)) == 0:
- chrome_args.remove('--remote-debugging-port=9222')
+ if s.connect_ex(('localhost', self.config.chrome_remote_debugging_port)) == 0:
+ chrome_args.remove(f'--remote-debugging-port={self.config.chrome_remote_debugging_port}')
browser_class = getattr(playwright, self.config.browser_class)
args = {
diff --git a/browser_use/browser/chrome.py b/browser_use/browser/chrome.py
index a829fc4ed..2f962c3e2 100644
--- a/browser_use/browser/chrome.py
+++ b/browser_use/browser/chrome.py
@@ -94,6 +94,8 @@ CHROME_DETERMINISTIC_RENDERING_ARGS = [
'--disable-back-forward-cache', # disable browsing navigation cache
]
+CHROME_DEBUGGING_ARG = '--remote-debugging-port=%(chrome_remote_debugging_port)s'
+
CHROME_ARGS = [
# Profile data dir setup
# chrome://profile-internals
@@ -128,7 +130,6 @@ CHROME_ARGS = [
'--log-level=2', # 1=DEBUG 2=WARNING 3=ERROR
'--enable-logging=stderr',
# '--remote-debugging-address=127.0.0.1', <- never expose to non-localhost, would allow attacker to drive your browser from any machine
- f'--remote-debugging-port={CHROME_DEBUG_PORT}',
'--enable-experimental-extension-apis', # add support for tab groups
'--disable-focus-on-load', # prevent browser from hijacking focus
'--disable-window-activation',
diff --git a/examples/custom-functions/file_upload.py b/examples/custom-functions/file_upload.py
index 827c0b637..d79f33cd5 100644
--- a/examples/custom-functions/file_upload.py
+++ b/examples/custom-functions/file_upload.py
@@ -70,7 +70,7 @@ async def read_file(path: str, available_file_paths: list[str]):
if path not in available_file_paths:
return ActionResult(error=f'File path {path} is not available')
- async with (await anyio.open_file(path, 'r')) as f:
+ async with await anyio.open_file(path, 'r') as f:
content = await f.read()
msg = f'File content: {content}'
logger.info(msg)
diff --git a/tests/test_browser.py b/tests/test_browser.py
index 9a24d6d51..4b2d56d04 100644
--- a/tests/test_browser.py
+++ b/tests/test_browser.py
@@ -1,6 +1,7 @@
import asyncio
import subprocess
+import psutil
import pytest
import requests
@@ -156,6 +157,82 @@ async def test_user_provided_browser_launch(monkeypatch):
await browser_obj.close()
+async def test_user_provided_browser_launch_on_custom_chrome_remote_debugging_port(monkeypatch):
+ """
+ Test that when a browser_binary_path and chrome_remote_debugging_port are provided, the Browser class uses
+ _setup_user_provided_browser branch and returns the expected DummyBrowser object
+ by launching a new Chrome instance with --remote-debugging-port=chrome_remote_debugging_port argument.
+ """
+
+ # Custom remote debugging port
+ custom_chrome_remote_debugging_port = 9223
+
+ # Dummy response for requests.get when checking chrome debugging endpoint.
+ class DummyResponse:
+ status_code = 200
+
+ def dummy_get(url, timeout):
+ if url == f'http://localhost:{custom_chrome_remote_debugging_port}/json/version':
+ return DummyResponse()
+ raise requests.ConnectionError('Connection failed')
+
+ monkeypatch.setattr(requests, 'get', dummy_get)
+
+ class DummyProcess:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ class DummySubProcess:
+ pid = 1234
+
+ async def dummy_create_subprocess_exec(browser_binary_path, *args, **kwargs):
+ assert f'--remote-debugging-port={custom_chrome_remote_debugging_port}' in args, (
+ f'Chrome must be started with with --remote-debugging-port={custom_chrome_remote_debugging_port} argument'
+ )
+
+ return DummySubProcess()
+
+ monkeypatch.setattr(asyncio, 'create_subprocess_exec', dummy_create_subprocess_exec)
+ monkeypatch.setattr(psutil, 'Process', DummyProcess)
+
+ class DummyBrowser:
+ pass
+
+ class DummyChromium:
+ async def connect_over_cdp(self, endpoint_url, timeout=20000):
+ assert endpoint_url == f'http://localhost:{custom_chrome_remote_debugging_port}', (
+ f"Endpoint URL must be 'http://localhost:{custom_chrome_remote_debugging_port}'"
+ )
+ return DummyBrowser()
+
+ class DummyPlaywright:
+ def __init__(self):
+ self.chromium = DummyChromium()
+
+ async def stop(self):
+ pass
+
+ class DummyAsyncPlaywrightContext:
+ async def start(self):
+ return DummyPlaywright()
+
+ monkeypatch.setattr('browser_use.browser.browser.async_playwright', lambda: DummyAsyncPlaywrightContext())
+
+ config = BrowserConfig(
+ browser_binary_path='dummy/chrome',
+ chrome_remote_debugging_port=custom_chrome_remote_debugging_port,
+ extra_browser_args=['--dummy-arg'],
+ )
+
+ browser_obj = Browser(config=config)
+ result_browser = await browser_obj.get_playwright_browser()
+ assert isinstance(result_browser, DummyBrowser), (
+ f'Expected DummyBrowser with remote debugging port {custom_chrome_remote_debugging_port} from _setup_user_provided_browser'
+ )
+ await browser_obj.close()
+
+
@pytest.mark.asyncio
async def test_builtin_browser_disable_security_args(monkeypatch):
"""