Block images

Block image requests with a route handler.

This example aborts PNG requests before the page loads.

Use it to see the mechanics of request blocking. In real tests, you might block large media, analytics, fonts, or third-party resources that do not affect the behavior under test.

Run it

bash
php content/examples/route-block-images.php

Expected output:

text
Loaded example.com with images blocked

The script only matches **/*.png. It does not block every image type. That narrow pattern is intentional: narrow routes are easier to reason about and do not need a continue() branch.

What it demonstrates

  • route() can intercept matching requests.
  • abort() cancels a request before the browser downloads it.
  • Routes must be registered before goto() to catch page-load requests.

If you need to block by resource type or host, use a broader route carefully and continue every request you do not abort.

Go next

Source

route-block-images.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;

$context = Playwright::chromium([
    'headless' => true,
]);
$page = $context->newPage();

// Block PNG images on this page
$page->route('**/*.png', function ($route): void {
    $route->abort();
});

$page->goto('https://example.com');
echo 'Loaded example.com with images blocked'.PHP_EOL;

$context->close();