Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Playwright Network Interception

Playwright Network Interception

Playwright's network interception (Network Interception) is a very useful capability in automation testing and web scraping scenarios, allowing us to intercept, modify, and simulate network requests and responses.

Playwright provides a page.route() and page.on('request') / page.on('response') and other APIs, allowing you to:

Common use cases:

Intercepting requests: page.route()



await page.route('**/api/todos', async route => {

  // Intercept matching requests

  console.log('拦截到请求:', route.request().url());



  // 1. Allow directly (continue request)

  await route.continue();



  // 2. Modify request

  // await route.continue({ headers: { ...route.request().headers(), 'X-Test': 'true' } });



  // 3. Return mock response

  // await route.fulfill({

  //   status: 200,

  //   contentType: 'application/json',

  //   body: JSON.stringify([{ id: 1, text: 'mock todo', done: false }]),

  // });



  // 4. Reject request

  // await route.abort();

});

Parameter Description:

Listen to requests and responses



// Listen to all requests

page.on('request', req => {

  console.log(`➡️ 请求: ${req.method()} ${req.url()}`);

});



// Listen to all responses

page.on('response', async res => {

  console.log(`⬅️ 响应: ${res.status()} ${res.url()}`);

});



// Get response body

const response = await page.waitForResponse('**/api/data');

console.log('响应内容:', await response.text());

// 2022-01-01 00:00:00 GMT:

Simulate network conditions

Example

// Simulate network errors

await page.

route

(

'**/*.png'

,

route

=>

route.

abort

(

'failed'

)

)

;

// Simulate latency

await page.

route

(

'/api/'

,

async route

=>

{

  await

new

Promise

(

r

=>

setTimeout

(

r

,

2000

)

)

;

  await route.

continue

(

)

;

}

)

;

pre

<

hr

<

h2

Complete example: Mock API

h2

import

{

test

,

expect

}

from

'@playwright/test'

;

test

(

'Intercept and mock API'

,

async

(

{

page

}

)

=>

{

 

// Intercept /api/todos requests and return fixed data

  await page.

route

(

'**/api/todos'

,

async route

=>

{

    await route.

fulfill

(

{

      status

:

200

,

      contentType

:

'application/json'

,

      body

:

JSON.

stringify

(

[

       

{

id

:

1

,

text

:

'Playwright Learning'

,

done

:

false

}

,

       

{

id

:

2

,

text

:

'Write automation tests'

,

done

:

true

}

,

     

]

)

,

   

}

)

;

 

}

)

;

  await page.

goto

(

'https://example-todo-app.com'

)

;

 

const

items

=

await page.

locator

(

'.todo-item'

)

.

allTextContents

(

)

;

  console.

log

(

'Loaded todos:'

,

items

)

;

 

// Assert UI displays mock data

  await expect

(

page.

locator

(

'.todo-item'

)

)

.

toHaveCount

(

2

)

;

  await expect

(

page.

locator

(

'.todo-item'

)

.

first

(

)

)

.

toContainText

(

'Playwright Learning'

)

;

}

)

;


Network interception related APIs

API Purpose Common parameters/descriptions
page.route(url, handler) Register request interception url Can be a string/regex/wildcard
route.request() Get request object Return Request
route.continue([options]) Continue request, can modify { method, headers, postData }
route.fulfill(response) Return a custom response { status, headers, body, contentType }
route.abort([errorCode]) Abort request Common:'failed', 'aborted', 'timedout'
page.unroute(url, handler?) Remove interception rule
page.on('request', cb) Listen to request
page.on('response', cb) Listen to response
request.url()/method()/headers()/postData() Request information
response.status()/headers()/text()/json() Response information
page.waitForResponse(urlOrPredicate) Wait for a specific response Can pass a URL or function