Sponsored Link
Looking for a unified way to  viewmonitor, and  debug Playwright Test Automation runs?
Try the Playwright Dashboard by today. Use the coupon code PWSOL10 for a 12 month 10% discount.

How to block ads during the execution of Playwright tests

Recently a site that I used for building out test automation examples added google ads to their site, which actually caused all of the tests I had written to fail. The ad one that popped up from the bottom and overlaid on top of the inputs the automation was interacting with.

To solve this problem I turned to the route method. This method allows you to create a way to interact with the network requests that come in. The route object allows the following:

  • abort - aborts the route's request
  • continue - continues the route's request with optional overrides. (ex: re-writing headers)
  • fulfill - fulfills the route's request with a given response. (ex: sending a different status code, content type or body). This could include sending mock data as the response.
  • request -  allows you to interact in many ways with the object.

For this specific example I wanted to write code that would find all the requests with the url that started with https://googleads.* and abort the requests, while continuing the remainder of the requests.

The following code block uses the context of the current session/test, and creates a route, that watches all the requests. The 2nd line of the code gets the request url as a string and uses the `startsWith()` function to return a boolean. If true, line 3 executes (abort), else line 4 executes (continue). Then the response is returned.

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

This block of code can also be helpful if you wanted to get a list of all the Network requests that are made on a page by modifying to print these out to the console. An important port of the code here is to do something with the request, in the below example I am continuing. If you don't use abort, continue, or fulfill the request will more than likely time out.

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

Enjoy!