|
2 | 2 | import logging
|
3 | 3 | import os
|
4 | 4 |
|
5 |
| -from browser_use.browser.browser import Browser |
| 5 | +from browser_use.browser.browser import Browser, IN_DOCKER |
6 | 6 | from browser_use.browser.context import BrowserContext, BrowserContextConfig
|
7 | 7 | from playwright.async_api import Browser as PlaywrightBrowser
|
8 | 8 | from playwright.async_api import BrowserContext as PlaywrightBrowserContext
|
9 | 9 |
|
10 | 10 | logger = logging.getLogger(__name__)
|
11 | 11 |
|
12 | 12 |
|
| 13 | +class CustomBrowserContextConfig(BrowserContextConfig): |
| 14 | + force_new_context: bool = False # force to create new context |
| 15 | + |
| 16 | + |
13 | 17 | class CustomBrowserContext(BrowserContext):
|
14 | 18 | def __init__(
|
15 | 19 | self,
|
16 | 20 | browser: "Browser",
|
17 |
| - config: BrowserContextConfig = BrowserContextConfig() |
| 21 | + config: CustomBrowserContextConfig = CustomBrowserContextConfig(), |
18 | 22 | ):
|
19 | 23 | super(CustomBrowserContext, self).__init__(browser=browser, config=config)
|
| 24 | + |
| 25 | + async def _create_context(self, browser: PlaywrightBrowser): |
| 26 | + """Creates a new browser context with anti-detection measures and loads cookies if available.""" |
| 27 | + if not self.config.force_new_context and self.browser.config.cdp_url and len(browser.contexts) > 0: |
| 28 | + context = browser.contexts[0] |
| 29 | + elif not self.config.force_new_context and self.browser.config.browser_binary_path and len( |
| 30 | + browser.contexts) > 0: |
| 31 | + # Connect to existing Chrome instance instead of creating new one |
| 32 | + context = browser.contexts[0] |
| 33 | + else: |
| 34 | + # Original code for creating new context |
| 35 | + context = await browser.new_context( |
| 36 | + no_viewport=True, |
| 37 | + user_agent=self.config.user_agent, |
| 38 | + java_script_enabled=True, |
| 39 | + bypass_csp=self.config.disable_security, |
| 40 | + ignore_https_errors=self.config.disable_security, |
| 41 | + record_video_dir=self.config.save_recording_path, |
| 42 | + record_video_size=self.config.browser_window_size.model_dump(), |
| 43 | + record_har_path=self.config.save_har_path, |
| 44 | + locale=self.config.locale, |
| 45 | + http_credentials=self.config.http_credentials, |
| 46 | + is_mobile=self.config.is_mobile, |
| 47 | + has_touch=self.config.has_touch, |
| 48 | + geolocation=self.config.geolocation, |
| 49 | + permissions=self.config.permissions, |
| 50 | + timezone_id=self.config.timezone_id, |
| 51 | + ) |
| 52 | + |
| 53 | + if self.config.trace_path: |
| 54 | + await context.tracing.start(screenshots=True, snapshots=True, sources=True) |
| 55 | + |
| 56 | + # Load cookies if they exist |
| 57 | + if self.config.cookies_file and os.path.exists(self.config.cookies_file): |
| 58 | + with open(self.config.cookies_file, 'r') as f: |
| 59 | + try: |
| 60 | + cookies = json.load(f) |
| 61 | + |
| 62 | + valid_same_site_values = ['Strict', 'Lax', 'None'] |
| 63 | + for cookie in cookies: |
| 64 | + if 'sameSite' in cookie: |
| 65 | + if cookie['sameSite'] not in valid_same_site_values: |
| 66 | + logger.warning( |
| 67 | + f"Fixed invalid sameSite value '{cookie['sameSite']}' to 'None' for cookie {cookie.get('name')}" |
| 68 | + ) |
| 69 | + cookie['sameSite'] = 'None' |
| 70 | + logger.info(f'🍪 Loaded {len(cookies)} cookies from {self.config.cookies_file}') |
| 71 | + await context.add_cookies(cookies) |
| 72 | + |
| 73 | + except json.JSONDecodeError as e: |
| 74 | + logger.error(f'Failed to parse cookies file: {str(e)}') |
| 75 | + |
| 76 | + # Expose anti-detection scripts |
| 77 | + await context.add_init_script( |
| 78 | + """ |
| 79 | + // Webdriver property |
| 80 | + Object.defineProperty(navigator, 'webdriver', { |
| 81 | + get: () => undefined |
| 82 | + }); |
| 83 | +
|
| 84 | + // Languages |
| 85 | + Object.defineProperty(navigator, 'languages', { |
| 86 | + get: () => ['en-US'] |
| 87 | + }); |
| 88 | +
|
| 89 | + // Plugins |
| 90 | + Object.defineProperty(navigator, 'plugins', { |
| 91 | + get: () => [1, 2, 3, 4, 5] |
| 92 | + }); |
| 93 | +
|
| 94 | + // Chrome runtime |
| 95 | + window.chrome = { runtime: {} }; |
| 96 | +
|
| 97 | + // Permissions |
| 98 | + const originalQuery = window.navigator.permissions.query; |
| 99 | + window.navigator.permissions.query = (parameters) => ( |
| 100 | + parameters.name === 'notifications' ? |
| 101 | + Promise.resolve({ state: Notification.permission }) : |
| 102 | + originalQuery(parameters) |
| 103 | + ); |
| 104 | + (function () { |
| 105 | + const originalAttachShadow = Element.prototype.attachShadow; |
| 106 | + Element.prototype.attachShadow = function attachShadow(options) { |
| 107 | + return originalAttachShadow.call(this, { ...options, mode: "open" }); |
| 108 | + }; |
| 109 | + })(); |
| 110 | + """ |
| 111 | + ) |
| 112 | + |
| 113 | + return context |
0 commit comments