Skip to content

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

Separate browser init methods in different functions

magmueller26c8874dd1d7
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.py
index c1eb2c256..15dbe76a2 100644
--- a/browser_use/browser/browser.py
+++ b/browser_use/browser/browser.py
@@ -74,6 +74,14 @@ class Browser:
self.playwright: Playwright | None = None
self.playwright_browser: PlaywrightBrowser | None = None
+ self.disable_security_args = []
+ if self.config.disable_security:
+ self.disable_security_args = [
+ '--disable-web-security',
+ '--disable-site-isolation-trials',
+ '--disable-features=IsolateOrigins,site-per-process',
+ ]
+
async def new_context(
self, config: BrowserContextConfig = BrowserContextConfig()
) -> BrowserContext:
@@ -97,94 +105,107 @@ class Browser:
return self.playwright_browser
- async def _setup_browser(self, playwright: Playwright) -> PlaywrightBrowser:
+ async def _setup_cdp(self, playwright: Playwright) -> PlaywrightBrowser:
"""Sets up and returns a Playwright Browser instance with anti-detection measures."""
- if self.config.cdp_url:
- # Loggin : Connecting to remote browser via CDP
- logger.info(f"Connecting to remote browser via CDP {self.config.cdp_url}")
- browser = await playwright.chromium.connect_over_cdp(self.config.cdp_url)
- return browser
- if self.config.wss_url:
- browser = await playwright.chromium.connect(self.config.wss_url)
- return browser
- elif self.config.chrome_instance_path:
- import subprocess
-
- import requests
-
- try:
- # Check if browser is already running
- response = requests.get('http://localhost:9222/json/version', timeout=2)
- if response.status_code == 200:
- logger.info('Reusing existing Chrome instance')
- browser = await playwright.chromium.connect_over_cdp(
- endpoint_url='http://localhost:9222',
- timeout=20000, # 20 second timeout for connection
- )
- return browser
- except requests.ConnectionError:
- logger.debug('No existing Chrome instance found, starting a new one')
-
- # Start a new Chrome instance
- subprocess.Popen(
- [
- self.config.chrome_instance_path,
- '--remote-debugging-port=9222',
- ],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- )
+ if not self.config.cdp_url:
+ raise ValueError('CDP URL is required')
+ logger.info(f'Connecting to remote browser via CDP {self.config.cdp_url}')
+ browser = await playwright.chromium.connect_over_cdp(self.config.cdp_url)
+ return browser
+
+ async def _setup_wss(self, playwright: Playwright) -> PlaywrightBrowser:
+ """Sets up and returns a Playwright Browser instance with anti-detection measures."""
+ if not self.config.wss_url:
+ raise ValueError('WSS URL is required')
+ logger.info(f'Connecting to remote browser via WSS {self.config.wss_url}')
+ browser = await playwright.chromium.connect(self.config.wss_url)
+ return browser
+
+ async def _setup_browser_with_instance(self, playwright: Playwright) -> PlaywrightBrowser:
+ """Sets up and returns a Playwright Browser instance with anti-detection measures."""
+ if not self.config.chrome_instance_path:
+ raise ValueError('Chrome instance path is required')
+ import subprocess
- # Attempt to connect again after starting a new instance
- try:
+ import requests
+
+ try:
+ # Check if browser is already running
+ response = requests.get('http://localhost:9222/json/version', timeout=2)
+ if response.status_code == 200:
+ logger.info('Reusing existing Chrome instance')
browser = await playwright.chromium.connect_over_cdp(
endpoint_url='http://localhost:9222',
timeout=20000, # 20 second timeout for connection
)
return browser
- except Exception as e:
- logger.error(f'Failed to start a new Chrome instance.: {str(e)}')
- raise RuntimeError(
- ' To start chrome in Debug mode, you need to close all existing Chrome instances and try again otherwise we can not connect to the instance.'
- )
+ except requests.ConnectionError:
+ logger.debug('No existing Chrome instance found, starting a new one')
+
+ # Start a new Chrome instance
+ subprocess.Popen(
+ [
+ self.config.chrome_instance_path,
+ '--remote-debugging-port=9222',
+ ],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+
+ # Attempt to connect again after starting a new instance
+ try:
+ browser = await playwright.chromium.connect_over_cdp(
+ endpoint_url='http://localhost:9222',
+ timeout=20000, # 20 second timeout for connection
+ )
+ return browser
+ except Exception as e:
+ logger.error(f'Failed to start a new Chrome instance.: {str(e)}')
+ raise RuntimeError(
+ ' To start chrome in Debug mode, you need to close all existing Chrome instances and try again otherwise we can not connect to the instance.'
+ )
- else:
- try:
- disable_security_args = []
- if self.config.disable_security:
- disable_security_args = [
- '--disable-web-security',
- '--disable-site-isolation-trials',
- '--disable-features=IsolateOrigins,site-per-process',
- ]
-
- browser = await playwright.chromium.launch(
- headless=self.config.headless,
- args=[
- '--no-sandbox',
- '--disable-blink-features=AutomationControlled',
- '--disable-infobars',
- '--disable-background-timer-throttling',
- '--disable-popup-blocking',
- '--disable-backgrounding-occluded-windows',
- '--disable-renderer-backgrounding',
- '--disable-window-activation',
- '--disable-focus-on-load',
- '--no-first-run',
- '--no-default-browser-check',
- '--no-startup-window',
- '--window-position=0,0',
- # '--window-size=1280,1000',
- ]
- + disable_security_args
- + self.config.extra_chromium_args,
- proxy=self.config.proxy,
- )
+ async def _setup_standard_browser(self, playwright: Playwright) -> PlaywrightBrowser:
+ """Sets up and returns a Playwright Browser instance with anti-detection measures."""
+ browser = await playwright.chromium.launch(
+ headless=self.config.headless,
+ args=[
+ '--no-sandbox',
+ '--disable-blink-features=AutomationControlled',
+ '--disable-infobars',
+ '--disable-background-timer-throttling',
+ '--disable-popup-blocking',
+ '--disable-backgrounding-occluded-windows',
+ '--disable-renderer-backgrounding',
+ '--disable-window-activation',
+ '--disable-focus-on-load',
+ '--no-first-run',
+ '--no-default-browser-check',
+ '--no-startup-window',
+ '--window-position=0,0',
+ # '--window-size=1280,1000',
+ ]
+ + self.disable_security_args
+ + self.config.extra_chromium_args,
+ proxy=self.config.proxy,
+ )
+ # convert to Browser
+ return browser
- return browser
- except Exception as e:
- logger.error(f'Failed to initialize Playwright browser: {str(e)}')
- raise
+ async def _setup_browser(self, playwright: Playwright) -> PlaywrightBrowser:
+ """Sets up and returns a Playwright Browser instance with anti-detection measures."""
+ try:
+ if self.config.cdp_url:
+ return await self._setup_cdp(playwright)
+ if self.config.wss_url:
+ return await self._setup_wss(playwright)
+ elif self.config.chrome_instance_path:
+ return await self._setup_browser_with_instance(playwright)
+ else:
+ return await self._setup_standard_browser(playwright)
+ except Exception as e:
+ logger.error(f'Failed to initialize Playwright browser: {str(e)}')
+ raise
async def close(self):
"""Close the browser instance"""