3.2 KiB
3.2 KiB
Working With Network
Playwright provides APIs to monitor and modify network traffic, both HTTP and HTTPS. Any requests that page does, including XHRs and fetch requests, can be tracked and modified.
NOTE As of playwright v0.13.0, Playwright is not yet capable of tracking websocket messages.
Monitor all network activity in page
const page = await browser.newPage();
page.on('request', request => console.log('>>', request.method(), request.url()));
page.on('response', response => console.log('<<', response.status(), response.url()));
await page.goto('https://example.com');
API reference
Wait for a response from API endpoint after button click
const [response] = await Promise.all([
page.waitForResponse('/api/fetch_data'),
page.click('button[type=submit]'),
]);
API reference
Mock API endpoint with test data
await page.route('/api/fetch_data', route => route.fulfill({
status: 200,
body: testData,
}));
await page.goto('https://example.com');
You can also use browserContext.route to mock
API endpoints for all the pages in the context.
API reference
Abort all images to speedup page load
const page = await browser.newPage();
await page.route('**/*.{png,jpg,jpeg}', route => route.abort());
await page.goto('https://example.com');
You can also use browserContext.route to abort
images for all pages in the context, including popups.
API reference
Setup HTTP authentication
const context = await browser.newContext({
httpCredentials: {
username: 'bill',
password: 'pa55w0rd',
},
});
const page = await context.newPage();
awat page.goto('https://example.com');
You can also use browserContext.setHTTPCredentials to update HTTP credentials of an existing context.
