Rayrun

How to Block Ads During the Execution of Playwright Tests

As a software QA engineer, you might encounter situations where ads interfere with your test automation scripts, causing unexpected failures. To ensure a smooth and efficient testing experience, we will examine several techniques to block ads using the Playwright framework.
  1. Methods to Block Ads
    1. Route Method
      1. Blocking Resources by Glob Pattern
        1. Blocking Resources by Regex
          1. Blocking Resources by Resource Type
          2. Logging Network Events
            1. Measuring Performance Boost
              1. HAR Files
                1. Browser's Performance API
                  1. CDP Session
                  2. Conclusion

                    Methods to Block Ads

                    Route Method

                    The route method helps you interact with network requests that come in during test execution. You can use this method to block specific requests or even manipulate the response, such as sending mock data. The route object has the following options:

                    • abort: Aborts the route's request.
                    • continue: Continues the route's request with optional overrides.
                    • fulfill: Fulfills the route's request with a given response.
                    • request: Allows you to interact with the request object.

                    To block ads during test execution, you can use the following code snippet to abort all requests with a URL starting with https://googleads.*:

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

                    Blocking Resources by Glob Pattern

                    Using the page.route method, you can block resources by matching the glob pattern of the request URL. For example, to block all SVGs from loading, you can use the following code snippet:

                    page.route("**/*.svg", (route) => {
                      route.abort();
                    });

                    Blocking Resources by Regex

                    If you prefer using regex to block resources, you can do so by first compiling the regex pattern. For instance, to block image resources with .jpg, .png, and .svg extensions, you can use the following code:

                    page.route(/.(jpg|png|svg)$/, (route) => {
                      route.abort();
                    }
                    );

                    Blocking Resources by Resource Type

                    You can also block resources based on their resource type. For example, to block all image resources, you can use the following code snippet:

                    page.route("**/*", (route) => {
                      if (route.request.resource_type == "image") {
                        route.abort()
                      } else {
                        route.continue();
                      }
                    });

                    Logging Network Events

                    To better understand the network requests and responses during test execution, you can log these events. Here's how to log network events in Playwright:

                    page.on("request", (request) => {
                      console.log(">>>", request.method, request.url, request.resource_type);
                    });
                    
                    page.on("response", (response) => {
                      console.log("<<<", response.status, response.url);
                    });

                    Measuring Performance Boost

                    By blocking ads and other unnecessary resources, you can improve the performance of your tests. Here are some methods to measure the performance boost:

                    HAR Files

                    Playwright allows you to record HAR files, which can be analyzed using Chrome DevTools or other HAR visualizers. To record a HAR file, use the following code snippet:

                    const page = browser.newPage({
                      recordHar: {
                        path: playwright_test.har,
                      }
                    });

                    Browser's Performance API

                    You can leverage the browser's performance API to measure the performance differences between blocking and non-blocking scenarios. To do this, use the following code:

                    page.goto("https://www.example.com/");
                    
                    console.log(page.evaluate("JSON.stringify(window.performance)"));

                    CDP Session

                    You can also use the Chrome DevTools Protocol (CDP) session to access performance metrics directly. Here's how to do it:

                    const client = await page.context.newCDPSession(page);
                    
                    await client.send("Performance.enable");
                    await page.goto("https://www.example.com/");
                    await console.log(client.send("Performance.getMetrics"));

                    Conclusion

                    Blocking ads during the execution of Playwright tests can significantly improve the performance and reliability of your test environment. By implementing the techniques discussed in this article, you can optimize your testing process and ensure a smoother experience. Remember, always measure the performance boost you achieve and adjust your strategies accordingly. Happy testing!

                    Thank you!
                    Was this helpful?

                    Now check your email!

                    To complete the signup, click the confirmation link in your inbox.

                    Subscribe to newsletter

                    You will receive a weekly email with the latest posts and QA jobs.

                    TwitterGitHubLinkedIn
                    AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

                    Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.