Skip to content

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

Keep screenshots and pointer actions in CSS coordinates

Magnus Mueller40166d3c07ac
diff --git a/browser_use/integrations/openai/browser_use.py b/browser_use/integrations/openai/browser_use.py
index d6db0c8f9..24d9673da 100644
--- a/browser_use/integrations/openai/browser_use.py
+++ b/browser_use/integrations/openai/browser_use.py
@@ -231,7 +231,16 @@ class BrowserUse:
async def screenshot(self, args: api.TabInput) -> dict[str, str]:
"""Capture the selected viewport as a native image input."""
page = await self._page(args['tab_id'])
- return {'type': 'input_image', 'image_url': 'data:image/png;base64,' + await page.screenshot(), 'detail': 'original'}
+ metrics = await self.browser.cdp_client.send.Page.getLayoutMetrics(session_id=await page.session_id)
+ viewport = metrics['cssVisualViewport']
+ size = (round(viewport['clientWidth']), round(viewport['clientHeight']))
+ data = await page.screenshot()
+ with Image.open(BytesIO(base64.b64decode(data))) as image:
+ if image.size != size:
+ output = BytesIO()
+ image.resize(size, Image.Resampling.LANCZOS).save(output, format='PNG')
+ data = base64.b64encode(output.getvalue()).decode()
+ return {'type': 'input_image', 'image_url': 'data:image/png;base64,' + data, 'detail': 'original'}
async def zoom(self, args: api.ZoomInput) -> dict[str, str]:
"""Crop a screenshot without changing the pointer coordinate origin."""
diff --git a/tests/ci/integrations/test_openai_browser_use.py b/tests/ci/integrations/test_openai_browser_use.py
index 43d77f508..4af68de82 100644
--- a/tests/ci/integrations/test_openai_browser_use.py
+++ b/tests/ci/integrations/test_openai_browser_use.py
@@ -197,3 +197,21 @@ async def test_sdk_accepts_uncommitted_tab_without_url(driver, monkeypatch):
assert all(tab['url'] == 'about:blank' for tab in result['state']['tabs'])
finally:
tools.close()
+
+
+async def test_screenshot_and_pointer_share_css_pixels_at_double_scale(driver):
+ page = await fixture_page(
+ driver,
+ """<button style="position:fixed;left:100px;top:100px;width:100px;height:50px;background:blue" onclick="document.title='Clicked'">Target</button>""",
+ )
+ await driver.browser.cdp_client.send.Emulation.setDeviceMetricsOverride(
+ {'width': 400, 'height': 300, 'deviceScaleFactor': 2, 'mobile': False},
+ session_id=await page.session_id,
+ )
+ screenshot = await driver.screenshot({'tab_id': None})
+ with Image.open(BytesIO(base64.b64decode(screenshot['image_url'].split(',', 1)[1]))) as image:
+ assert image.size == (400, 300)
+ assert image.convert('RGB').getpixel((110, 110)) == (0, 0, 255)
+ await driver.click_at({'tab_id': None, 'x': 150, 'y': 125, 'button': 'left', 'click_count': 1, 'keys': []})
+ assert await page.evaluate('() => document.title') == 'Clicked'