Tuesday, April 29, 2025

How to block ads during the execution of Playwright tests

Playwright is a powerful tool for browser automation, ideal for testing and web scraping. However, when automating websites, ads can slow down your scripts, clutter the interface, or even cause test flakiness. Fortunately, you can block ads in Playwright with just a few lines of code.

In this post, you'll learn how to block ads using two primary techniques: route interception and browser extensions.

How to block ads during the execution of Playwright tests


 Syntax to block ads using route

The following code block uses the context of the current session/test, and creates a route, that watches all the requests.

await context.route("**/*", (request) => {
   request.request().url().startsWith("https://googleads.")
      ? request.abort()
      : request.continue();
    return;
  });

 Syntax to print all network request in console

In this example, it will get a list of all the Network requests and print in console.

await context.route("**/*", (request) => {
  console.log(request.request().url())
  request.continue();
  return;
});


Block Ads Using Route Interception

Playwright allows you to intercept network requests and block or modify them before they’re sent. Here's how to use this to block common ad providers.

import { test, expect } from '@playwright/test';
import { chromium } from 'playwright';

test('disable ads in playwright', async ({ page }) => {
  
const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  // List of URL patterns to block (add more as needed)
  const blockedResources = [
    'googlesyndication.com',
    'adservice.google.com',
    'doubleclick.net',
    'adsystem.com',
    'amazon-adsystem.com'
  ];

  await page.route('**/*', (route) => {
    const url = route.request().url();
    if (blockedResources.some(resource => url.includes(resource))) {
      return route.abort();
    }
    route.continue();
  });

  await page.goto('https://www.skptricks.com');
  await page.screenshot({ path: 'no-ads.png' });

  await browser.close();

});

Blocking ads in Playwright helps speed up automation and reduce distractions in tests and data scraping. For simple needs, intercepting network requests is enough. If you need full ad blocking like a regular user experience, loading an extension like uBlock Origin is your best bet.


No comments:

Post a Comment