How to simulate slow network speed in puppeteer
To simulate network throttling in Puppeteer, you can use the setOfflineMode
and setRequestInterception
methods provided by the Puppeteer Page
class. Here’s how you can simulate different network conditions like slow 3G:
- Simulating Network Throttling (Slow 3G):
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Enable request interception
await page.setRequestInterception(true);
// Intercept requests and simulate slow 3G
page.on('request', (request) => {
const headers = request.headers();
headers['Connection'] = 'close'; // Close connection to simulate slow network
request.continue({ headers });
});
// Navigate to a website
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
// Your Puppeteer script continues here
await browser.close();
})();
Explanation:
-
setRequestInterception(true)
: This method enables request interception, allowing you to modify requests before they are sent. -
page.on('request', ...)
: Sets up an event listener for requests. Here, you modify the request headers to simulate a slow network connection by closing the connection. -
page.goto('https://example.com', { waitUntil: 'domcontentloaded' })
: Navigates to the specified URL. You can adjust the URL to your testing needs. -
Browser Closure: Always close the Puppeteer browser instance using
browser.close()
after your script completes its tasks.
Adjusting Network Conditions:
To simulate different network conditions, you can modify the headers in the page.on('request', ...)
handler:
- Slow 3G: Use
headers['Connection'] = 'close';
to simulate slow network speed by delaying responses. - Offline Mode: Use
page.setOfflineMode(true);
to simulate being offline, which will cause all requests to fail.