How do you resize the browser dynamically at runtime in Playwright during an E2E test?

In Protractor, I could resize the browser window at runtime using:

browser.driver.manage().window().setSize(width - 30, height);

I want to achieve the same behavior in Playwright, adjust the viewport size dynamically while running an end-to-end test. How can I set or change the viewport size during test execution using Playwright?

In Playwright, you can change the viewport size at runtime with page.setViewportSize(). For example:

await page.setViewportSize({ width: 1024, height: 768 });

// Later in the test, resize again
await page.setViewportSize({ width: 1280, height: 800 });

This is similar to what you did in Protractor but scoped to the page rather than the browser window. It works immediately during test execution.

Another approach is to create a new context if you need different sizes in separate parts of the test:

const context = await browser.newContext({ viewport: { width: 1200, height: 700 } });
const page = await context.newPage();
await page.goto('https://example.com');

// If needed, create another context with a different viewport
const mobileContext = await browser.newContext({ viewport: { width: 375, height: 667 } });
const mobilePage = await mobileContext.newPage();

This is handy if you want to simulate different devices without affecting the original page.

Sometimes you might want to dynamically adjust the viewport and capture screenshots:

await page.setViewportSize({ width: 1024, height: 768 });
await page.screenshot({ path: 'desktop.png' });

await page.setViewportSize({ width: 375, height: 667 });
await page.screenshot({ path: 'mobile.png' });

This ensures your E2E tests cover multiple screen sizes dynamically, just like in responsive testing.