Network

You can also use to update HTTP credentials of an existing context.

API reference

Handle file downloads

  1. const [ download ] = await Promise.all([
  2. page.waitForEvent('download'), // <-- start waiting for the download
  3. page.click('button#delayed-download') // <-- perform the action that directly or indirectly initiates it.
  4. ]);
  5. const path = await download.path();

For every attachment downloaded by the page, event is emitted. If you create a browser context with the acceptDownloads: true, all these attachments are going to be downloaded into a temporary folder. You can obtain the download url, file system path and payload stream using the Download object from the event.

Variations

  1. page.on('download', download => download.path().then(console.log));

Note that handling the event forks the control flow and makes script harder to follow. Your scenario might end while you are downloading a file since your main control flow is not awaiting for this operation to resolve.

API reference

You can monitor all the requests and responses:

  1. // Use a glob URL pattern
  2. const [response] = await Promise.all([
  3. page.waitForResponse('**/api/fetch_data'),
  4. page.click('button#update'),
  5. ]);

Variations

  1. const [response] = await Promise.all([
  2. page.waitForResponse(/\.jpeg$/),
  3. page.click('button#update'),
  4. ]);
  5. // Use a predicate taking a Response object
  6. const [response] = await Promise.all([
  7. page.waitForResponse(response => response.url().includes(token)),
  8. page.click('button#update'),
  9. ]);

API reference

Handle requests

You can mock API endpoints via handling the network quests in your Playwright script.

Variations

  1. // It will apply to popup windows and opened links.
  2. status: 200,
  3. body: 'accept',
  4. }));
  5. await page.goto('https://example.com');

API reference

  1. // Delete header
  2. await page.route('**/*', route => {
  3. const headers = route.request().headers();
  4. delete headers['X-Secret'];
  5. route.continue({headers});
  6. });
  7. // Continue requests as POST.
  8. await page.route('**/*', route => route.continue({method: 'POST'}));

You can continue requests with modifications. Example above removes an HTTP header from the outgoing requests.

Abort requests

API reference