Playwright Intercept Request

Profile picture for user arilio666

In Playwright, you can intercept a network request by using the route method of a page or browserContext object. The route method accepts a URL pattern to match against incoming requests and a callback function to be invoked when the pattern is met. You can modify the request or response in the callback function, or you can cancel the request entirely.

Playwright Intercept Request
  • From the diagram, we can understand how a request is made when the browser invokes it.
  • GET method is requested. In turn, the response with status 200 and the requested content is provided to the browser.

Modifying Requests

 await page.route('**/*', route => {
    const url = route.request().url().replace('programsbuzz.com', 'article.com');
           route.continue({ url });
});          
         
await page.goto('https://www.programsbuzz.com/');
  • In the above example, we intercept all requests ('**/*') and modify the URL by replacing programsbuzz.com with article.com. We use the continue method to continue with the modified request.
Playwright Intercept Request

Canceling Requests

await page.route('**/*.{png,jpeg,jpg,webp,svg}', (route, request) => route.abort() );

await page.goto('https://www.programsbuzz.com/')

This route aborts any png, jpeg, jpg, or any other site interfaces to abort from loading, as we clearly mentioned in the route to abort.

await page.route(/(analytics|fonts)/, (route, request) => route.abort() );

We can use it to remove custom fonts from the site. All these can speed up the test script to perform its job smoothly without aborting because of load time.

Block Requests

await page.route('**/*', route => {
 if (route.request().method() === 'POST') {
   route.abort();
 } else {
   route.continue();
 }
});
  • In this example, we block all POST requests by aborting them and allow all other requests to continue.