Skip to content

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

Fix browser_window_size not changing window size in non-headless mode

Sandeep Salwanb4133b8912f8
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.py
index db9ec7b77..11c5996bb 100644
--- a/browser_use/browser/browser.py
+++ b/browser_use/browser/browser.py
@@ -321,7 +321,7 @@ class Browser:
args=args[self.config.browser_class],
proxy=self.config.proxy.model_dump() if self.config.proxy else None,
handle_sigterm=False,
- handle_sigint=False
+ handle_sigint=False,
)
return browser
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index ef6769c68..72346c820 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -43,30 +43,13 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-# Constants
-# Default height adjustment for browser chrome (title bar, tabs, etc.)
-# This can vary by platform, browser, and display settings
-BROWSER_CHROME_HEIGHT_DEFAULT = 85
-BROWSER_CHROME_HEIGHT_WINDOWS = 85
-BROWSER_CHROME_HEIGHT_MACOS = 80
-BROWSER_CHROME_HEIGHT_LINUX = 90
-
-def get_browser_chrome_height() -> int:
- """Determine appropriate browser chrome height based on platform"""
- import platform
- system = platform.system().lower()
-
- if system == 'darwin':
- return BROWSER_CHROME_HEIGHT_MACOS
- elif system == 'windows':
- return BROWSER_CHROME_HEIGHT_WINDOWS
- elif system == 'linux':
- return BROWSER_CHROME_HEIGHT_LINUX
- else:
- return BROWSER_CHROME_HEIGHT_DEFAULT
-
-# Get the appropriate chrome height for current platform
-BROWSER_CHROME_HEIGHT = get_browser_chrome_height()
+import platform
+
+BROWSER_NAVBAR_HEIGHT = {
+ 'windows': 85,
+ 'darwin': 80,
+ 'linux': 90,
+}.get(platform.system().lower(), 85)
class BrowserContextWindowSize(BaseModel):
@@ -476,19 +459,28 @@ class BrowserContext:
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])
+ for page in context.pages:
+ await self._set_viewport_size_for_page(page)
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 one
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])
+ for page in context.pages:
+ await self._set_viewport_size_for_page(page)
else:
kwargs = {}
# 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
+ # Only set viewport in headless mode, let window size define viewport in headful mode
+ if self.browser.config.headless:
+ kwargs['viewport'] = self.config.browser_window_size.model_dump()
+ kwargs['no_viewport'] = False
+ else:
+ # In headful mode, let the window size set the viewport
+ kwargs['no_viewport'] = True
if self.config.user_agent is not None:
kwargs['user_agent'] = self.config.user_agent
@@ -1757,14 +1749,14 @@ class BrowserContext:
'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)
+ 'height': window_size['height'] + BROWSER_NAVBAR_HEIGHT, # Add height for browser chrome
+ 'windowState': 'normal', # Ensure window is not minimized/maximized
},
},
)
await cdp_session.detach()
- logger.debug(f'Set window size to {window_size["width"]}x{window_size["height"] + BROWSER_CHROME_HEIGHT}')
+ logger.debug(f'Set window size to {window_size["width"]}x{window_size["height"] + BROWSER_NAVBAR_HEIGHT}')
except Exception as e:
logger.debug(f'CDP window resize failed: {e}')
@@ -1777,10 +1769,10 @@ class BrowserContext:
}
""",
window_size['width'],
- window_size['height'] + BROWSER_CHROME_HEIGHT
+ window_size['height'] + BROWSER_NAVBAR_HEIGHT,
)
logger.debug(
- f'Used JavaScript to set window size to {window_size["width"]}x{window_size["height"] + BROWSER_CHROME_HEIGHT}'
+ f'Used JavaScript to set window size to {window_size["width"]}x{window_size["height"] + BROWSER_NAVBAR_HEIGHT}'
)
except Exception as e:
logger.debug(f'JavaScript window resize failed: {e}')
diff --git a/examples/browserDemo.py b/tests/test_browser_window_size_height.py
similarity index 84%
rename from examples/browserDemo.py
rename to tests/test_browser_window_size_height.py
index 79e30e12f..1c3fa5345 100644
--- a/examples/browserDemo.py
+++ b/tests/test_browser_window_size_height.py
@@ -19,7 +19,7 @@ async def main():
browser = None
browser_context = None
-
+
try:
# Initialize the browser with error handling
try:
@@ -29,14 +29,14 @@ async def main():
)
)
except Exception as e:
- print(f"Failed to initialize browser: {e}")
+ print(f'Failed to initialize browser: {e}')
return 1
# Create a browser context
try:
browser_context = await browser.new_context(config=config)
except Exception as e:
- print(f"Failed to create browser context: {e}")
+ print(f'Failed to create browser context: {e}')
return 1
# Get the current page
@@ -47,8 +47,8 @@ async def main():
await page.goto('https://example.com')
await page.wait_for_load_state('domcontentloaded')
except Exception as e:
- print(f"Failed to navigate to example.com: {e}")
- print("Continuing with test anyway...")
+ print(f'Failed to navigate to example.com: {e}')
+ print('Continuing with test anyway...')
# Wait a bit to see the window
await asyncio.sleep(2)
@@ -65,19 +65,19 @@ async def main():
print(f'Configured window size: {window_size.model_dump()}')
print(f'Actual viewport size: {viewport_size}')
-
+
# Validate the window size
validate_window_size(window_size.model_dump(), viewport_size)
# Wait a bit more to see the window
await asyncio.sleep(3)
-
+
return 0
except Exception as e:
- print(f"Unexpected error: {e}")
+ print(f'Unexpected error: {e}')
return 1
-
+
finally:
# Close resources
if browser_context:
@@ -91,16 +91,16 @@ def validate_window_size(configured: Dict[str, Any], actual: Dict[str, Any]) ->
# Allow for small differences due to browser chrome, scrollbars, etc.
width_diff = abs(configured['width'] - actual['width'])
height_diff = abs(configured['height'] - actual['height'])
-
+
# Tolerance of 5% or 20px, whichever is greater
width_tolerance = max(configured['width'] * 0.05, 20)
height_tolerance = max(configured['height'] * 0.05, 20)
-
+
if width_diff > width_tolerance or height_diff > height_tolerance:
- print("WARNING: Significant difference between configured and actual window size!")
- print(f"Width difference: {width_diff}px, Height difference: {height_diff}px")
+ print('WARNING: Significant difference between configured and actual window size!')
+ print(f'Width difference: {width_diff}px, Height difference: {height_diff}px')
else:
- print("Window size validation passed: actual size matches configured size within tolerance")
+ print('Window size validation passed: actual size matches configured size within tolerance')
if __name__ == '__main__':