Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Fix browser_window_size not changing window size in non-headless mode
Sandeep Salwana10d7e428831
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.pyindex 2ddaa6ee1..fb3d31578 100644--- a/browser_use/browser/browser.py+++ b/browser_use/browser/browser.py@@ -27,7 +27,7 @@ from browser_use.browser.chrome import (CHROME_HEADLESS_ARGS,)from browser_use.browser.context import BrowserContext, BrowserContextConfig-from browser_use.browser.utils.screen_resolution import get_screen_resolution, get_window_adjustments+from browser_use.browser.utils.screen_resolution import get_window_adjustments, get_screen_resolutionfrom browser_use.utils import time_execution_asynclogger = logging.getLogger(__name__)@@ -251,7 +251,15 @@ class Browser:"""Sets up and returns a Playwright Browser instance with anti-detection measures."""assert self.config.browser_binary_path is None, 'browser_binary_path should be None if trying to use the builtin browsers'- if self.config.headless:+ # Use the configured window size from new_context_config if available+ if (+ not self.config.headless+ and hasattr(self.config, 'new_context_config')+ and hasattr(self.config.new_context_config, 'browser_window_size')+ ):+ screen_size = self.config.new_context_config.browser_window_size.model_dump()+ offset_x, offset_y = get_window_adjustments()+ elif self.config.headless:screen_size = {'width': 1920, 'height': 1080}offset_x, offset_y = 0, 0else:@@ -291,6 +299,15 @@ class Browser:],}+ # Add viewport size to launch options for non-headless mode+ viewport = None+ if (+ not self.config.headless+ and hasattr(self.config, 'new_context_config')+ and hasattr(self.config.new_context_config, 'browser_window_size')+ ):+ viewport = self.config.new_context_config.browser_window_size.model_dump()+browser = await browser_class.launch(headless=self.config.headless,channel='chrome',@@ -383,4 +400,4 @@ class Browser:try:await client.aclose()except Exception as e:- logger.debug(f'Error closing httpx client: {e}')+ logger.debug(f'Error closing httpx client: {e}')\ No newline at end of filediff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex 9b3772a23..01832690b 100644--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@ -43,6 +43,8 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+# Constants+BROWSER_CHROME_HEIGHT = 85 # Height adjustment for browser chrome (title bar, tabs, etc.)class BrowserContextWindowSize(BaseModel):"""Window size configuration for browser context"""@@ -228,7 +230,7 @@ class BrowserSession:if (!this.__listeners[type]) {this.__listeners[type] = [];}-+// Add the listener to __listenersthis.__listeners[type].push({@@ -403,6 +405,13 @@ class BrowserContext:await active_page.bring_to_front()await active_page.wait_for_load_state('load')+ # Set the viewport size for the active page+ try:+ await active_page.set_viewport_size(self.config.browser_window_size.model_dump())+ logger.debug(f'Set viewport size to {self.config.browser_window_size.width}x{self.config.browser_window_size.height}')+ except Exception as e:+ logger.debug(f'Failed to set viewport size: {e}')+self.active_tab = active_pagereturn self.session@@ -442,14 +451,22 @@ class BrowserContext:"""Creates a new browser context with anti-detection measures and loads cookies if available."""if self.browser.config.cdp_url and len(browser.contexts) > 0 and not self.config.force_new_context:context = browser.contexts[0]+ # For existing contexts, we need to set the viewport size manually+ if context.pages and not self.browser.config.headless:+ await self._set_viewport_size_for_page(context.pages[0])elif self.browser.config.browser_binary_path and len(browser.contexts) > 0 and not self.config.force_new_context:# Connect to existing Chrome instance instead of creating new onecontext = browser.contexts[0]+ # For existing contexts, we need to set the viewport size manually+ if context.pages and not self.browser.config.headless:+ await self._set_viewport_size_for_page(context.pages[0])else:kwargs = {}- if self.browser.config.headless:- kwargs['viewport'] = self.config.browser_window_size.model_dump()- kwargs['no_viewport'] = False+ # Set viewport for both headless and non-headless modes+ kwargs['viewport'] = self.config.browser_window_size.model_dump()+ # Important: set no_viewport to False to ensure the viewport size is applied+ kwargs['no_viewport'] = False+if self.config.user_agent is not None:kwargs['user_agent'] = self.config.user_agent@@ -472,6 +489,10 @@ class BrowserContext:if self.config.trace_path:await context.tracing.start(screenshots=True, snapshots=True, sources=True)+ # Resize the window for non-headless mode+ if not self.browser.config.headless and not self.config.no_viewport:+ await self._resize_window(context)+# Load cookies if they existif self.config.cookies_file and os.path.exists(self.config.cookies_file):async with await anyio.open_file(self.config.cookies_file, 'r') as f:@@ -508,6 +529,13 @@ class BrowserContext:return context+ async def _set_viewport_size_for_page(self, page: Page) -> None:+ """Helper method to set viewport size for a page"""+ try:+ await page.set_viewport_size(self.config.browser_window_size.model_dump())+ except Exception as e:+ logger.debug(f'Failed to set viewport size for page: {e}')+async def _wait_for_stable_network(self):page = await self.get_current_page()@@ -1489,6 +1517,13 @@ class BrowserContext:await page.bring_to_front()await page.wait_for_load_state()+ # Set the viewport size for the tab+ try:+ await page.set_viewport_size(self.config.browser_window_size.model_dump())+ logger.debug(f'Set viewport size to {self.config.browser_window_size.width}x{self.config.browser_window_size.height}')+ except Exception as e:+ logger.debug(f'Failed to set viewport size: {e}')+@time_execution_async('--create_new_tab')async def create_new_tab(self, url: str | None = None) -> None:"""Create a new tab and optionally navigate to a URL"""@@ -1502,6 +1537,13 @@ class BrowserContext:await new_page.wait_for_load_state()+ # Set the viewport size for the new tab+ try:+ await new_page.set_viewport_size(self.config.browser_window_size.model_dump())+ logger.debug(f'Set viewport size to {self.config.browser_window_size.width}x{self.config.browser_window_size.height}')+ except Exception as e:+ logger.debug(f'Failed to set viewport size: {e}')+if url:await new_page.goto(url)await self._wait_for_page_and_frames_load(timeout_overwrite=1)@@ -1662,6 +1704,63 @@ class BrowserContext:logger.debug(f'Failed to get CDP targets: {e}')return []+ async def _resize_window(self, context: PlaywrightBrowserContext) -> None:+ """Resize the browser window to match the configured size"""+ try:+ if not context.pages:+ return++ page = context.pages[0]+ window_size = self.config.browser_window_size.model_dump()++ # First, set the viewport size+ try:+ await page.set_viewport_size(window_size)+ logger.debug(f'Set viewport size to {window_size["width"]}x{window_size["height"]}')+ except Exception as e:+ logger.debug(f'Viewport resize failed: {e}')++ # Then, try to set the actual window size using CDP+ try:+ cdp_session = await context.new_cdp_session(page)++ # Get the window ID+ window_id_result = await cdp_session.send('Browser.getWindowForTarget')++ # Set the window bounds+ await cdp_session.send(+ 'Browser.setWindowBounds',+ {+ 'windowId': window_id_result['windowId'],+ 'bounds': {+ 'width': window_size['width'],+ 'height': window_size['height'] + BROWSER_CHROME_HEIGHT, # Add height for browser chrome+ 'windowState': 'normal', # Ensure window is in normal state (not minimized/maximized)+ },+ },+ )++ await cdp_session.detach()+ logger.debug(f'Set window size to {window_size["width"]}x{window_size["height"] + BROWSER_CHROME_HEIGHT}')+ except Exception as e:+ logger.debug(f'CDP window resize failed: {e}')++ # Fallback to using JavaScript+ try:+ await page.evaluate(f"""+ () => {{+ window.resizeTo({window_size['width']}, {window_size['height'] + BROWSER_CHROME_HEIGHT});+ }}+ """)+ logger.debug(f'Used JavaScript to set window size to {window_size["width"]}x{window_size["height"] + BROWSER_CHROME_HEIGHT}')+ except Exception as e:+ logger.debug(f'JavaScript window resize failed: {e}')++ logger.debug(f'Attempted to resize window to {window_size["width"]}x{window_size["height"]}')+ except Exception as e:+ logger.debug(f'Failed to resize browser window: {e}')+ # Non-critical error, continue execution+async def wait_for_element(self, selector: str, timeout: float) -> None:"""Waits for an element matching the given CSS selector to become visible.@@ -1674,4 +1773,4 @@ class BrowserContext:TimeoutError: If the element does not become visible within the specified timeout."""page = await self.get_current_page()- await page.wait_for_selector(selector, state='visible', timeout=timeout)+ await page.wait_for_selector(selector, state='visible', timeout=timeout)\ No newline at end of filediff --git a/examples/browserDemo.py b/examples/browserDemo.pynew file mode 100644index 000000000..16087c1fc--- /dev/null+++ b/examples/browserDemo.py@@ -0,0 +1,58 @@+"""+Example script demonstrating the browser_window_size feature.+This script shows how to set a custom window size for the browser.+"""++import asyncio+from browser_use.browser.browser import Browser, BrowserConfig+from browser_use.browser.context import BrowserContextConfig, BrowserContextWindowSize+++async def main():+ """Demonstrate setting a custom browser window size"""+ # Create a browser with a specific window size+ window_size = BrowserContextWindowSize(width=800, height=400) # Small size to clearly demonstrate the fix+ config = BrowserContextConfig(browser_window_size=window_size)++ browser = Browser(+ config=BrowserConfig(+ headless=False, # Use non-headless mode to see the window+ )+ )++ try:+ # Create a browser context+ browser_context = await browser.new_context(config=config)++ # Get the current page+ page = await browser_context.get_current_page()++ # Navigate to a test page+ await page.goto('https://example.com')++ # Wait a bit to see the window+ await asyncio.sleep(2)++ # Get the actual viewport size using JavaScript+ viewport_size = await page.evaluate("""+ () => {+ return {+ width: window.innerWidth,+ height: window.innerHeight+ }+ }+ """)++ print(f'Configured window size: {window_size.model_dump()}')+ print(f'Actual viewport size: {viewport_size}')++ # Wait a bit more to see the window+ await asyncio.sleep(3)++ finally:+ # Close the browser+ await browser.close()+++if __name__ == '__main__':+ asyncio.run(main())\ No newline at end of file