ScreenshotNeo

BlogHow-to

How to Set and Check Selenium Browser Window Size

Set Selenium’s browser dimensions, verify the result, handle headless and remote environments, and troubleshoot window-size mismatches.

By the ScreenshotNeo team30 September 20266 min read

How to Set and Check Selenium Browser Window Size

Use WebDriver’s window-management commands. In Python, call driver.set_window_size(width, height), then verify with driver.get_window_size(). When you also need the window position, use driver.set_window_rect() and driver.get_window_rect().

Set the size before navigating to the page state whose responsive behavior you are testing. Read the dimensions back and log them because operating systems, window managers, headless mode and remote grids can reinterpret outer-window dimensions.

Python: set and check the browser size

from selenium import webdriver


driver = webdriver.Chrome()
try:
    driver.set_window_size(1024, 768)

    size = driver.get_window_size()
    assert size["width"] == 1024
    assert size["height"] == 768

    driver.get("https://example.com")
finally:
    driver.quit()

set_window_size(width, height) takes pixel dimensions. get_window_size() returns the current width and height. See the Selenium Python WebDriver API for the binding reference.

Read the complete window rectangle

driver.set_window_rect(width=1000, height=700)
rect = driver.get_window_rect()

assert rect["width"] == 1000
assert rect["height"] == 700
print(rect)  # x, y, width and height

set_window_rect() can set only the fields you need, or all four fields:

driver.set_window_rect(x=40, y=40, width=1200, height=800)
rect = driver.get_window_rect()
print(rect)

Rect commands are W3C-compatible. In older or non-W3C environments, use the separate position and size methods when a rect command is unavailable.

Which dimensions are you setting?

Need Python call What it returns
Width and height set_window_size() Set the outer browser window dimensions
Current width and height get_window_size() Dictionary containing width and height
Position plus dimensions set_window_rect() Sets any combination of x, y, width and height
Current position plus dimensions get_window_rect() Dictionary containing all rectangle fields

These are outer-window values. The page’s CSS viewport can be smaller because of browser chrome, operating-system borders, scaling and device-pixel-ratio settings. If your test depends on a CSS breakpoint, measure the viewport in the page as well:

Selenium controls the outer window; verify the resulting CSS viewport separately.
Selenium controls the outer window; verify the resulting CSS viewport separately.
viewport = driver.execute_script("""
return {
  width: window.innerWidth,
  height: window.innerHeight,
  devicePixelRatio: window.devicePixelRatio
};
""")
print(viewport)

Set the size before navigation

  1. Create the driver and apply the requested size.
  2. Read the size or rect back and record it in test logs.
  3. Navigate to the page.
  4. Wait for the responsive state or target element.
  5. Capture screenshots or assert the layout.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait


driver = webdriver.Chrome()
try:
    driver.set_window_size(1280, 900)
    print("window:", driver.get_window_rect())

    driver.get("https://example.com")
    WebDriverWait(driver, 10).until(
        lambda d: d.find_element(By.TAG_NAME, "body").is_displayed()
    )

    css_viewport = driver.execute_script(
        "return {width: innerWidth, height: innerHeight}"
    )
    print("viewport:", css_viewport)
finally:
    driver.quit()

Other Selenium language bindings

The Selenium window-management guide documents equivalent APIs for the major bindings. The guide also notes that screen resolution can affect how an application renders: Working with windows and tabs.

Java

import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

WebDriver driver = new ChromeDriver();
try {
    driver.manage().window().setSize(new Dimension(1024, 768));
    Dimension size = driver.manage().window().getSize();
    System.out.println(size.getWidth() + "x" + size.getHeight());
} finally {
    driver.quit();
}

C#

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

IWebDriver driver = new ChromeDriver();
try
{
    driver.Manage().Window.Size = new Size(1024, 768);
    Size size = driver.Manage().Window.Size;
    Console.WriteLine($"{size.Width}x{size.Height}");
}
finally
{
    driver.Quit();
}

Ruby

require "selenium-webdriver"

driver = Selenium::WebDriver.for :chrome
begin
  driver.manage.window.resize_to(1024, 768)
  size = driver.manage.window.size
  puts "#{size.width}x#{size.height}"
ensure
  driver.quit
end

JavaScript

const { Builder } = require('selenium-webdriver');

(async function () {
  const driver = await new Builder().forBrowser('chrome').build();
  try {
    await driver.manage().window().setRect({ width: 1024, height: 768 });
    const rect = await driver.manage().window().getRect();
    if (rect.width <= 0 || rect.height <= 0) {
      throw new Error(`Invalid window rectangle: ${JSON.stringify(rect)}`);
    }
    console.log(rect);
  } finally {
    await driver.quit();
  }
})();

Kotlin

import org.openqa.selenium.Dimension
import org.openqa.selenium.chrome.ChromeDriver

val driver = ChromeDriver()
try {
    driver.manage().window().size = Dimension(1024, 768)
    println(driver.manage().window().size)
} finally {
    driver.quit()
}

Headless, CI and remote-grid behavior

Exact outer-window equality is environment-dependent. Selenium’s documentation says that the exact behavior is specific to individual window managers. A headed local browser, a Linux CI runner, a container and a remote grid may return different outer dimensions for the same request.

  • Prefer a fixed viewport contract when the test is about responsive CSS.
  • Log get_window_rect(), innerWidth, innerHeight and devicePixelRatio.
  • Use positive-range or breakpoint assertions when the environment cannot honor exact outer dimensions.
  • Apply the size after creating the session and before loading the page.
  • Do not confuse browser window pixels with screenshot bitmap pixels; retina or device scale can change the bitmap size.

Common errors and fixes

Error or symptom Likely cause Fix
AttributeError for a window method Wrong binding or an outdated Selenium package Upgrade Selenium and use the API for your language. Python uses driver.set_window_size(); JavaScript uses setRect().
Returned size differs from the requested size Window manager, headless mode, remote grid or OS constraints Log the rect and assert the dimensions your test contract requires. Measure innerWidth for CSS behavior.
Responsive breakpoint does not change Size was applied after navigation, or the viewport is constrained Set the window before navigation and inspect window.innerWidth.
Window is larger than the screen Desktop environment limits the outer window Choose dimensions supported by the runner or use a viewport-specific browser option.
Screenshot has unexpected pixel dimensions Device scale factor or browser screenshot semantics Compare CSS viewport dimensions with bitmap dimensions and record device-pixel ratio.
Remote session rejects rect commands Older driver or non-W3C endpoint Use separate position and size commands, update the driver, or select a W3C-compatible session.

Performance, reliability and cost considerations

  • Window resizing is inexpensive compared with starting a browser session and loading a page, so reuse a driver when tests can share a stable viewport.
  • For parallel tests, assign one viewport contract per session to avoid race conditions from two tests resizing the same window.
  • Record the requested size and the read-back rect in CI logs; this makes layout failures diagnosable.
  • Use explicit waits for layout-critical elements instead of relying on a fixed sleep.
  • Keep viewport sizes consistent across screenshot baselines. A changed OS scale factor can alter rendered pixels even when CSS dimensions match.

Or skip the browser setup

If your goal is a clean page image rather than browser interaction, ScreenshotNeo provides a single screenshot request. Its API accepts viewport and device options, full-page capture, CSS selectors, dark mode, retina scale, custom CSS and JavaScript, waits, headers, cookies, blocking rules, caching and more. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' }); const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners, popups and chat widgets are removed before the shot. Bot checks, blank pages and failed loads are never billed, and response headers identify the page verdict and billing result. An MCP server lets AI agents use take_screenshot, get_page_info and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

FAQ

Does Selenium set the viewport or the outer window?

The window commands set the browser window dimensions. The resulting CSS viewport can be smaller because of browser chrome and the operating system.

ScreenshotNeo removes common overlays before returning the screenshot.
ScreenshotNeo removes common overlays before returning the screenshot.

Should I use set_window_size or set_window_rect?

Use set_window_size for width and height only. Use rect commands when position and dimensions belong to the same operation.

How do I verify a responsive breakpoint?

Set the size before navigation, read back the rect, then measure window.innerWidth and assert the breakpoint-specific state.

Why does the same test produce different screenshots in CI?

Screen resolution, window managers, device scale, browser versions and remote-grid settings can all affect rendering. Log both outer rect and CSS viewport values.