How to Intercept Requests in Playwright

On this page

When we browse the web, a series of HTTP requests and responses are exchanged between our browser and the pages we are visiting. There are scenarios in which it is useful to monitor or manipulate this traffic.

Request interception

Request interception enables us to observe which requests and responses are being exchanged as part of our script’s execution. For example, this is how we could print them out when we load our test website:


const { chromium } = require('playwright')

;(async () => {
  const browser = await chromium.launch()
  const page = await browser.newPage()

  await page.setViewportSize({ width: 1200, height: 800 })

  page.on('request', (request) =>
    console.log('>>', request.method(), request.url())
  )
  page.on('response', (response) =>
    console.log('<<', response.status(), response.url())
  )

  await page.goto('https://danube-web.shop/')

  await page.screenshot({ path: 'screenshot.png' })

  await browser.close()
})()


Run in Checkly

We might want to intervene and filter the outgoing requests. For example, when scraping web pages, we might want to block unnecessary elements from loading in order to speed up the procedure and lower bandwidth usage.


const { chromium } = require('playwright')

;(async () => {
  const browser = await chromium.launch()
  const page = await browser.newPage()

  await page.setViewportSize({ width: 1200, height: 800 })

  await page.route('**/*', (route) => {
    return route.request().resourceType() === 'image'
      ? route.abort()
      : route.continue()
  })

  await page.goto('https://danube-web.shop/')

  await page.screenshot({ path: 'screenshot.png' })

  await browser.close()
})()


Run in Checkly

Last updated on September 30, 2024. You can contribute to this documentation by editing this page on Github