The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →In Playwright, “screen size” can mean two different measurements. Use page.viewportSize() for the configured page viewport, or evaluate window.screen.width and window.screen.height for the dimensions exposed through the browser’s Screen API.
The distinction matters in responsive tests: viewport dimensions control the page’s rendering area, while Screen API dimensions are values that application JavaScript reads. The examples below show how to read, configure, assert, and troubleshoot both.
Choose the measurement you actually need
Before writing a locator or assertion, decide which coordinate system your test concerns:
| Measurement | Read it with | Configured at | Best use |
|---|---|---|---|
| Viewport | page.viewportSize() |
Page or browser-context viewport settings | Verifying the CSS rendering area used by the test |
| Screen | window.screen.width and window.screen.height |
Browser-context screen option |
Testing code that reads the Screen API |
| Device scale factor | Context emulation settings | Browser context or device descriptor | Testing pixel density; it is not a width or height |
Playwright’s Page API documents viewportSize(), while the Browser API documents context-level viewport and screen emulation.
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
Get the configured viewport size
Call page.viewportSize() and inspect the returned object. Width and height are CSS pixels. The method returns null when no consistent viewport is configured.
import { test, expect } from '@playwright/test';
test('reads the configured viewport', async ({ page }) => {
const viewport = page.viewportSize();
console.log(viewport); // { width: 1280, height: 720 }, for example
expect(viewport).not.toBeNull();
expect(viewport?.width).toBe(1280);
expect(viewport?.height).toBe(720);
});
Because the return type can be null, avoid immediately dereferencing viewport.width in reusable helpers. Handle the unset case explicitly:
function requireViewport(page: import('@playwright/test').Page) {
const viewport = page.viewportSize();
if (!viewport) {
throw new Error('This test requires an explicit Playwright viewport');
}
return viewport;
}
test('uses a non-null viewport', async ({ page }) => {
const { width, height } = requireViewport(page);
console.log(`Viewport: ${width}x${height}`);
});
Use this value when the assertion is about the dimensions Playwright assigned to the page. It is not a reading of the monitor, operating-system window, or browser chrome.
Get the browser’s Screen API dimensions
For dimensions available to code running inside the page, evaluate the Screen API in the page context:
const screenSize = await page.evaluate(() => ({
width: window.screen.width,
height: window.screen.height,
}));
console.log(screenSize); // { width: 1440, height: 900 }, for example
This is the correct approach when the application itself branches on window.screen.width or window.screen.height. It is intentionally different from page.viewportSize(): one is a page-side browser value and the other is Playwright’s configured rendering viewport.
You can assert the values directly:
test('application sees the expected Screen dimensions', async ({ page }) => {
const screenSize = await page.evaluate(() => ({
width: window.screen.width,
height: window.screen.height,
}));
expect(screenSize).toEqual({ width: 1440, height: 900 });
});
Configure viewport and screen dimensions together
Set both values when a test needs deterministic rendering and deterministic Screen API values. The screen option is used when a viewport is set.
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
import { chromium } from 'playwright';
const browser = await chromium.launch();
const context = await browser.newContext({
viewport: { width: 1280, height: 800 },
screen: { width: 1440, height: 900 },
});
const page = await context.newPage();
await page.goto('https://example.com');
console.log(page.viewportSize());
console.log(await page.evaluate(() => ({
width: window.screen.width,
height: window.screen.height,
})));
await browser.close();
The viewport controls the visible CSS layout area. The context’s screen setting controls the dimensions exposed through window.screen. Keep the two values intentionally different only when that mismatch is part of the behavior you are testing.
Context settings apply to pages created from that context, so create the context before newPage(). The Pages guide describes this context-level emulation model.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Resize an existing page with setViewportSize()
For a single page, call page.setViewportSize({ width, height }):
await page.setViewportSize({ width: 1024, height: 768 });
const viewport = page.viewportSize();
console.log(viewport); // { width: 1024, height: 768 }
Playwright recommends setting the viewport before navigation when the site makes startup decisions from the device size:
const page = await context.newPage();
await page.setViewportSize({ width: 390, height: 844 });
await page.goto('https://example.com');
Changing the page viewport also resets the screen size. If you need controlled values for both measurements, prefer the context-level viewport and screen options shown above. This behavior is documented in the Page API.
Set the viewport in Playwright Test
For Playwright Test, put the viewport in the project’s configuration so every fixture page starts consistently:
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
viewport: { width: 1280, height: 800 },
},
});
The documented Playwright Test default viewport is 1280 × 720. A project that relies on a different size should declare it rather than depending on the default. The TestOptions API documents the default and the null behavior.
Setting viewport: null opts out of consistent viewport emulation. The resulting size depends on the host window, which makes test execution non-deterministic. Use this only when host-window behavior is the subject of the test; for ordinary responsive checks, use explicit dimensions.
If your test needs a particular Screen API value as well as a viewport, create a browser context with both options in a setup fixture rather than changing the page after navigation.
Device descriptors: viewport, screen, and scale are separate
Playwright device descriptors can supply a viewport, screen size, and other device characteristics. A descriptor may also set deviceScaleFactor. Scale factor changes pixel density; it does not change the CSS width or height returned by page.viewportSize().
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsWhen a test depends on a descriptor’s exact numbers, inspect the actual values used by the project instead of assuming a device name implies a particular viewport or screen. The device emulation guide, currently labeled “Next,” shows descriptor overrides and scale-factor configuration; verify version-sensitive details against the stable documentation used by your project: device emulation guide.
Generated tests can also carry a viewport-size setting. Playwright’s Codegen guide documents the viewport-size option; review the generated configuration rather than treating codegen output as a universal default.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Write assertions that match the requirement
Testing responsive layout
Assert the viewport, then assert a user-visible layout or locator. A viewport number alone does not prove that a breakpoint rendered the intended component.
test('mobile layout uses the configured viewport', async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto('https://example.com');
expect(page.viewportSize()).toEqual({ width: 390, height: 844 });
await expect(page.getByRole('button', { name: 'Menu' })).toBeVisible();
});
Testing code that reads window.screen
Configure screen on the context and evaluate the values in the page. Do not substitute the viewport assertion, because the application may see different numbers.
Testing several sizes
Use a table-driven loop so each size is explicit and failures identify the exact case:
const viewports = [
{ name: 'phone', width: 390, height: 844 },
{ name: 'tablet', width: 768, height: 1024 },
{ name: 'desktop', width: 1440, height: 900 },
];
for (const size of viewports) {
test(`renders at ${size.name}`, async ({ page }) => {
await page.setViewportSize({ width: size.width, height: size.height });
await page.goto('https://example.com');
expect(page.viewportSize()).toEqual({ width: size.width, height: size.height });
});
}
Common problems and fixes
viewportSize() is null
The page has no consistent viewport, commonly because the context or test configuration used viewport: null. Set an explicit viewport before reading it, or handle the nullable result if host-window behavior is intentional.
The Screen API value is not what the test expects
Check that the context was created with a screen option and that a viewport is also set. Then evaluate window.screen in the same page under test. A context created without the option will not provide the emulated dimensions you intended.
Changing the viewport changed screen dimensions
This is expected: setViewportSize() resets screen size. Configure both values on browser.newContext() when they must remain controlled.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
The page took the wrong responsive branch
Set the viewport before goto(). Some applications choose navigation, load different assets, or calculate breakpoints during startup; resizing after navigation can leave startup decisions unchanged.
Assertions vary between machines or CI workers
Look for viewport: null, an inherited project override, or a device descriptor that supplies its own values. Declare explicit dimensions in the project configuration and log both page.viewportSize() and the evaluated Screen API object when diagnosing a failure.
Width and height look right but screenshots differ
Check device scale factor and other emulation settings separately. Screen size and viewport dimensions do not describe pixel density, fonts, operating-system rendering, or every device characteristic.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Performance and reliability notes
Both reads are local operations: page.viewportSize() returns Playwright’s current configuration, and the Screen API evaluation executes a small function in the already-running page. They do not require an additional network request. Navigation remains the expensive part of a realistic test, so read dimensions after the page is created and avoid repeated resizing when one configured context can cover the scenario.
For reliable CI, keep viewport dimensions explicit, set them before navigation, and keep assertions tied to the measurement your application uses. If a test must model a real device, record the descriptor and scale-factor settings alongside the viewport and screen values so a later failure can be reproduced.
Or skip the browser setup
If your actual goal is a clean visual capture rather than reading dimensions inside a Playwright test, ScreenshotNeo can return a screenshot or PDF from one request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. It also provides an MCP server for Claude, Cursor, and other MCP clients with take_screenshot, get_page_info, and capture_pdf tools.
Use the API documentation for all parameters and options: ScreenshotNeo API docs.
cURL
curl -G "https://api.screenshotneo.com/v1/shot"
-d access_key=YOUR_API_KEY
--data-urlencode url=https://stripe.com
-o shot.webp
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const data = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', data));
ScreenshotNeo includes full-page captures with lazy images loaded, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF controls, custom CSS and JavaScript, pre-capture clicks, selector hiding, selector/delay/network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, an OpenAPI specification, and compatibility with parameter names used by other screenshot APIs.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Every feature is available on every plan:
| Plan | Included shots | Price |
|---|---|---|
| Free | 1,000 per month | $0, no card |
| Starter | 3,000 | $5 |
| Growth | 15,000 | $15 |
| Pro | 60,000 | $39 |
| Scale | 250,000 | $99 |
| Business | 1,000,000 | $249 |
Yearly billing provides two months free. If a hosted screenshot fits your workflow, sign up for ScreenshotNeo to get 1,000 screenshots a month free with no card; paid plans start at $5 for 3,000 screenshots.
Bottom line
Use page.viewportSize() for Playwright’s configured viewport. Evaluate window.screen.width and window.screen.height when the application’s Screen API values are what matter. Configure explicit context dimensions before navigation for repeatable tests, and treat device scale factor as a separate setting.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

