Network Snippets
Network features within the Puppeteer library allow you to interact with network requests - this can be useful for intercepting network requests from sites to either log, test, or block resources.
# Blocking resources
Resources can either all be blocked, or individual resource types can be blocked. This can be useful to speed up your automations to prevent the browser from loading elements of the page that you may not need, such as images, or ad libraries. This code should go before your "Go to page" step of your automation, preferably as the first step within a "Write Javascript" step.
Note: blocking resources cause issues on pages, use with caution.
await page.setRequestInterception(true);
page.on('request', request => {
// Check if the request has been intercepted elsewhere, useful if you have multiple listeners.
if (request.isInterceptResolutionHandled()) return;
// Block any request ending with '.png' or '.jpg' - images
if (request.url().endsWith('.png') || request.url().endsWith('.jpg')) {
request.abort('failed', 0);
} else {
request.continue();
}
})
While we used images as an example above, there are many ways that you can block resources, simply modify the 'if' statement to match your requirements, for example, to block a url:
if (request.url().startsWith('https://google.com')) {
request.abort('failed', 0);
}
Or if you want to block full request resource types:
if (request.resourceType() === 'font') {
request.abort('failed', 0)
}
There are many resource types to choose from, but remember to take care when experimenting with them:
font, block the loading of fontsscript, block the loading of Javascript files (not recommended)images, block the loading of imagesvideo, block the loading of videos
You can find a full list in Mozilla's Resource Type (opens new window) documentation.