Network
You can also use to update HTTP credentials of an existing context.
API reference
Handle file downloads
const [ download ] = await Promise.all([
page.waitForEvent('download'), // <-- start waiting for the download
page.click('button#delayed-download') // <-- perform the action that directly or indirectly initiates it.
]);
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
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:
// Use a glob URL pattern
const [response] = await Promise.all([
page.waitForResponse('**/api/fetch_data'),
page.click('button#update'),
]);
Variations
const [response] = await Promise.all([
page.waitForResponse(/\.jpeg$/),
page.click('button#update'),
]);
// Use a predicate taking a Response object
const [response] = await Promise.all([
page.waitForResponse(response => response.url().includes(token)),
page.click('button#update'),
]);
API reference
Handle requests
You can mock API endpoints via handling the network quests in your Playwright script.
Variations
// It will apply to popup windows and opened links.
status: 200,
body: 'accept',
}));
await page.goto('https://example.com');
API reference
// Delete header
await page.route('**/*', route => {
const headers = route.request().headers();
delete headers['X-Secret'];
route.continue({headers});
});
// Continue requests as POST.
await page.route('**/*', route => route.continue({method: 'POST'}));
You can continue requests with modifications. Example above removes an HTTP header from the outgoing requests.