User Agents

Web browsers and everyday web tech, explained

Intercept Image Requests in Puppeteer and Playwright

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Intercepting image requests in headless Chrome allows developers to block images to speed up page load times, replace assets for testing, or monitor which images are being requested by a web application. By leveraging the request interception APIs in Puppeteer and Playwright, you can evaluate every network request the browser makes and decide whether to allow it, abort it, or modify the response before it reaches the page.

What You'll Need

  • Node.js installed on your local machine.
  • A code editor (such as VS Code).
  • The puppeteer or playwright npm package installed in your project.
  • Basic familiarity with asynchronous JavaScript (async/await).

Step-by-Step

Intercepting Images with Puppeteer

  1. Initialize the Browser: Launch your browser instance and create a new page object.
  2. Enable Request Interception: Call await page.setRequestInterception(true);. This tells Puppeteer to pause all requests and wait for your manual instruction to continue or abort.
  3. Set up the Request Listener: Use page.on('request', (request) => { ... }) to create a handler that triggers every time a network request is initiated.
  4. Filter by Resource Type: Inside the listener, check the resource type using request.resourceType(). If the type equals 'image', you can handle it specifically.
  5. Abort or Continue: To block the image, call request.abort();. To allow it to load normally, call request.continue();.
  6. Navigate to the Page: Use await page.goto(url);. The interception logic will now apply to all images loaded during the navigation.

Intercepting Images with Playwright

  1. Launch the Browser: Start your browser and create a browser context.
  2. Use route(): Playwright uses a more modern routing system. Call await page.route('**/*', (route) => { ... }). The '**/*' pattern ensures all URLs are captured.
  3. Inspect the Request: Inside the route handler, access the request object via route.request().
  4. Check Resource Type: Use route.request().resourceType() to determine if the request is for an image.
  5. Abort or Fulfill: To block the image, call route.abort();. If you want to replace the image with a local file or a mock response, use route.fulfill({ path: 'mock-image.png' });. Otherwise, call route.continue();.
  6. Navigate: Use await page.goto(url); to execute the page load with the routing rules active.

Common Mistakes

  • Forgetting to call continue(): In Puppeteer, if you enable request interception but fail to call request.continue() or request.abort() for a request, the page will hang indefinitely because the request is stuck in a pending state.
  • Applying interception after navigation: If you call page.goto() before setting up your setRequestInterception or route handlers, the initial batch of images will load before the filter is active.
  • Over-blocking: Blocking all images can sometimes break the functionality of a site if the site uses images (like transparent 1x1 pixels) for tracking or triggering specific JavaScript events.
  • Ignoring Case Sensitivity: While resource types are generally standardized, always ensure you are comparing strings accurately (e.g., using 'image' in lowercase).

Tips

  • Performance Gains: Blocking images is one of the fastest ways to reduce bandwidth and CPU usage during web scraping or automated testing.
  • Mocking Assets: Instead of just blocking, use Playwright's route.fulfill() to serve a consistent, small placeholder image. This prevents layout shifts (CLS) that might occur when images are completely missing.
  • Selective Blocking: Instead of blocking all images, check the request.url() to block only specific domains or file extensions (like .gif or .webp).
  • Logging: Log the URLs of intercepted images to a CSV or JSON file to create a map of all assets used by a target website.

Troubleshooting

If images are still loading despite your interception code, check the following:

  • Timing: Ensure the interception logic is defined before the goto command.
  • Scope: In Playwright, if you are using multiple pages or contexts, ensure the route is applied to the specific page or the entire browserContext.
  • Cache: Sometimes images are loaded from the browser cache rather than the network. Try disabling the cache using await page.setCacheEnabled(false); in Puppeteer.
  • Resource Type Mismatch: Some images may be delivered as 'fetch' or 'xhr' requests if they are loaded via Base64 or Blob URLs. Check the network tab in a standard browser to see how the images are actually being requested.

Frequently Asked Questions

Does blocking images speed up Puppeteer scripts?

Yes, significantly. By preventing the browser from downloading and rendering image files, you reduce network latency and memory consumption, leading to faster execution times.

Can I replace an image with a different one?

Yes. In Playwright, you can use route.fulfill() to provide a custom response body or a path to a local image file, effectively swapping the asset on the fly.

Is there a difference between blocking images and hiding them via CSS?

Yes. Hiding images via CSS (e.g., display: none) still requires the browser to download the image. Intercepting the request prevents the download entirely, saving bandwidth.

Will this work for images loaded via CSS background-image?

Yes. Both Puppeteer and Playwright intercept the network request regardless of whether the image is triggered by an <img> tag or a CSS property.

Can I intercept images in non-headless mode?

Yes. Request interception works exactly the same way whether the browser is running in headless mode or headed mode.