Home  Playwright   Interceptin ...

Intercepting network requests in Playwright

Intercepting webpage requests in Playwright is straightforward and powerful. You can use the page.route() method to intercept and modify network requests and responses. This feature is useful for mocking network responses, blocking resources, or inspecting request details.

Here's a step-by-step guide on how to intercept webpage requests in Playwright:

Example

Let's say you want to intercept all network requests to a specific URL and log their details.

Playwright Script to Intercept Requests

Here's a script to intercept requests and log their details:

const { chromium } = require('playwright');

(async () => {
  // Launch the browser
  const browser = await chromium.launch();
  
  // Create a new browser context
  const context = await browser.newContext();
  
  // Create a new page
  const page = await context.newPage();
  
  // Intercept requests
  await page.route('**/*', (route, request) => {
    console.log('Request URL:', request.url());
    console.log('Request Method:', request.method());
    console.log('Request Headers:', request.headers());
    console.log('Request Post Data:', request.postData());
    
    // Continue the request without modifications
    route.continue();
  });
  
  // Navigate to a webpage
  await page.goto('https://example.com');
  
  // Close the browser
  await browser.close();
})();

Explanation

  1. Launch the Browser:

    const browser = await chromium.launch();
    
  2. Create a New Browser Context:

    const context = await browser.newContext();
    
  3. Create a New Page:

    const page = await context.newPage();
    
  4. Intercept Requests:

    await page.route('**/*', (route, request) => {
      console.log('Request URL:', request.url());
      console.log('Request Method:', request.method());
      console.log('Request Headers:', request.headers());
      console.log('Request Post Data:', request.postData());
      
      // Continue the request without modifications
      route.continue();
    });
    
    • page.route('**/*', (route, request) => { ... }) intercepts all network requests.
    • Inside the callback function, you can log request details (url, method, headers, postData).
    • route.continue() continues the request without modifications. You can also modify or block the request if needed.
  5. Navigate to a Webpage:

    await page.goto('https://example.com');
    
  6. Close the Browser:

    await browser.close();
    

Additional Features

Running the Script

Save the script to a file (e.g., intercept_requests.js) and execute it using Node.js:

node intercept_requests.js

This script demonstrates how to intercept and log network requests in Playwright. You can customize the interception logic to suit your testing or automation needs.

Published on: Jun 28, 2024, 03:22 AM  
 

Comments

Add your comment