Skip to main content

setViewport

Overview​

Set the size of the page viewport and its device pixel ratio. Unlike setWindowSize, this changes the area used to render the page, not the outer browser window.

Usage​

browser.setViewport({ width, height, devicePixelRatio })

Parameters​

ParameterTypeDefaultDescription
widthnumberRequiredViewport width in CSS pixels.
heightnumberRequiredViewport height in CSS pixels.
devicePixelRationumber1The device pixel ratio (DPR). Omitting it sets DPR to 1.

Result​

Promise<void>.

Limitations​

Requires WebDriver BiDi (webSocketUrl: true) and a driver that supports viewport resizing. Run the command in the top-level document. If a test has switched into an iframe, return with switchFrame(null) first.

Use integer dimensions in CSS pixels and a positive DPR. In @testplane/webdriverio 9.6.2 the client checks width and height against 0 and Number.MAX_SAFE_INTEGER; the driver can reject a size within that range. Save both dimensions and DPR if you need to restore them. Changing the viewport does not enable touch input or change the browser engine.

Example​

Set baseUrl to your local HTTP test site, where / returns an HTML page. Run the example in a regular Testplane test file.

const assert = require("node:assert/strict");

it("setViewport: change page dimensions", async ({ browser }) => {
await browser.url("/");
const original = await browser.execute(() => ({
width: innerWidth,
height: innerHeight,
devicePixelRatio,
}));
try {
await browser.setViewport({ width: 800, height: 600, devicePixelRatio: 2 });
const viewport = await browser.execute(() => [innerWidth, innerHeight, devicePixelRatio]);
assert.deepEqual(viewport, [800, 600, 2]);
} finally {
await browser.setViewport(original);
}
});

See also​