Change the viewport

Read and change the viewport, then screenshot each size.

This example starts with a 1200×800 viewport, captures a screenshot, then changes the viewport to 1920×1080 and captures another screenshot.

Use it to understand the difference between initial context/page viewport and resizing during a run.

Run it

bash
php content/examples/viewport-size.php

Expected output:

text
Current viewport: 1200x800
Screenshot saved to: .../var/playwright-artifacts/examples/viewport_1200x800.png
New viewport: 1920x1080
Screenshot saved to: .../var/playwright-artifacts/examples/viewport_1920x1080.png

The screenshots are written to the examples artifact directory.

What it demonstrates

  • newPage() can receive an initial viewport.
  • viewportSize() reads the current size.
  • setViewportSize() changes the viewport during the run.
  • Reloading after resize can expose responsive layout differences.

For mobile behavior, prefer device or context configuration before navigation.

Go next

Source

viewport-size.php
php
<?php

declare(strict_types=1);

/*
 * This file is part of the community-maintained Playwright PHP project.
 * It is not affiliated with or endorsed by Microsoft.
 *
 * (c) 2025-Present - Playwright PHP - https://github.com/playwright-php
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require_once __DIR__.'/../../vendor/autoload.php';

use Playwright\Playwright;

$artifactDir = __DIR__.'/../../var/playwright-artifacts/examples';
is_dir($artifactDir) || mkdir($artifactDir, 0777, true);

// Headless can be set to false to see the browser
$context = Playwright::chromium(['headless' => true]);

$page = $context->newPage(['viewport' => ['width' => 1200, 'height' => 800]]);

$page->goto('https://howbigismybrowser.com/');

$viewport = $page->viewportSize();
echo sprintf('Current viewport: %dx%d', $viewport['width'], $viewport['height'])."\n";

$screenshot = $page->screenshot($artifactDir.'/viewport_1200x800.png');
echo 'Screenshot saved to: '.$screenshot."\n";

// Change viewport size at runtime
$page->setViewportSize(1920, 1080);
$page->reload();

$viewport = $page->viewportSize();
echo sprintf('New viewport: %dx%d', $viewport['width'], $viewport['height'])."\n";

$screenshot = $page->screenshot($artifactDir.'/viewport_1920x1080.png');
echo 'Screenshot saved to: '.$screenshot."\n";

$page->close();
$context->close();