Headless browsers
Block images and fonts in Playwright, keep scripts and CSS
Block images, media and fonts by resource type in Playwright when you only need a page's text, and see why scripts, data calls and stylesheets stay on.
By Cerys Eaton, SiteRender team · Published
This article was drafted with AI assistance from the sources listed below and edited and published by the SiteRender team. Disclosure: the SiteRender API, which this article mentions, is this site's own product.
- Match on resourceType, not on file extensions
- Abort image, media and font
- Keep script, xhr, fetch and stylesheet
- Use context.route so popups are covered too
- Set serviceWorkers to block so routes see every request
- Count requests by type before and after
You render a page in Playwright to read its text, and the browser downloads every hero image, video and web font on the way. None of it ends up in the string you store. Blocking those requests is the standard fix. Doing it by file extension, or blocking too much, gives you a different result than the one you meant to get.
The headless browser guide shows a one-line extension filter. This post goes one step further: what to match on, what to keep, and the side effects of turning interception on at all.
Match on resource type, not on the extension
Symptom: you block **/*.{png,jpg,jpeg,webp} and images still load.
Playwright's glob has to match the entire URL. A single * stops at /, and ? in a glob matches only a literal question mark. So https://example.com/img/hero.jpg?w=800 does not match **/*.jpg, and neither does an image served from /img/hero with no extension, or a format you did not list.
Check the type instead. request.resourceType() reports the type as the rendering engine perceived it. The values are document, stylesheet, image, media, font, script, texttrack, xhr, fetch, eventsource, websocket, manifest, beacon, ping, cspreport and other.
// read-text.mjs: npm install playwright
import { chromium } from "playwright";
const BLOCK = new Set(["image", "media", "font"]);
const browser = await chromium.launch();
const context = await browser.newContext({ serviceWorkers: "block" });
await context.route("**/*", (route) =>
BLOCK.has(route.request().resourceType())
? route.abort("blockedbyclient")
: route.continue()
);
const page = await context.newPage();
await page.goto("https://example.com/", { waitUntil: "domcontentloaded" });
await page.locator("body p").first().waitFor({ timeout: 15_000 });
console.log(await page.locator("body").innerText());
await browser.close();
Verdict: one route on **/* with a type check catches what the extension list missed.
Why scripts and data calls stay on
You use a browser for this page because its text is built after load. The script requests carry that code, and xhr and fetch requests carry the data it renders. Block them and the text that code builds never arrives.
If the text you need is already in that HTML, skip the browser entirely. The one-minute test tells you which case you have.
Why stylesheets stay on too
Blocking CSS looks like a free saving. It is not, if you read with innerText.
MDN describes innerText as aware of the rendered appearance of text, where textContent is not: hidden elements, such as a span with display: none, are left out. That hiding often comes from CSS rules. Abort them and the CSS that hid a mobile menu or a closed dialog never arrives, so that text can show up in your result.
node read-text.mjs > with-css.txt
# add "stylesheet" to BLOCK, run again
node read-text.mjs > without-css.txt
diff with-css.txt without-css.txt | head -40
Lines that appear only in without-css.txt are text the site meant to hide. Keep stylesheet off the block list.
Run the same diff with font on the block list to confirm the text does not change on your page.
Side effects of turning on routing
Three notes from Playwright's page.route docs matter for a text read:
- The HTTP cache is off. Enabling routing disables the HTTP cache. If one context opens many pages from the same site, the shared scripts and stylesheets are downloaded again for each page. Measure whether blocking still comes out ahead for your URLs.
- Service workers hide requests. Routes do not see requests that a service worker intercepts. The docs recommend setting
serviceWorkersto"block"when you intercept, which the example above does. - Popups slip past page routes.
page.route()does not intercept the first request of a popup page; the docs point tobrowserContext.route()instead, which is why the example routes on the context.
Two smaller ones. If a request matches several routes, the one registered last wins, and page routes win over context routes. And route.abort() defaults to the error code failed; passing blockedbyclient ("The client chose to block the request.") makes the intent readable when you log failed requests.
Test it yourself
Count requests by type on your own page before you decide what to block:
// count-types.mjs
import { chromium } from "playwright";
const counts = {};
const browser = await chromium.launch();
const page = await browser.newPage();
page.on("request", (r) => {
counts[r.resourceType()] = (counts[r.resourceType()] ?? 0) + 1;
});
await page.goto("https://example.com/", { waitUntil: "load" });
console.table(counts);
await browser.close();
Then compare the text from read-text.mjs with and without the route. Same text, and most requests were image, media or font: the block list pays off. Different text: something on the list was doing more than decoration.
Fewer browser pages beats lighter ones
Blocking images makes each rendered page cheaper. Not rendering a page at all is cheaper still. SiteRender API works that way: it tries a fast fetch first and renders a page in a real browser only when that fetch cannot read it. To check whether a static fetch is enough for a URL, try it in the playground.
Render public pages only, and keep to robots.txt, the site's terms and reasonable request rates.
Frequently asked questions
How do I block images in Playwright?
Register a route for every URL and abort the requests whose resourceType is image, for example context.route('**/*', route => route.request().resourceType() === 'image' ? route.abort() : route.continue()). Matching on the resource type also catches images whose URLs have no file extension or end in a query string.
Why does my glob like **/*.{png,jpg} not block all images?
Playwright's glob must match the entire URL, and a question mark in a glob only matches a literal question mark. An image URL that ends in a query string such as ?w=800, or that has no extension, does not match the pattern, so the request goes through.
Can I block JavaScript in Playwright to save more?
You can, but on a page that builds its content in the browser, the scripts and the data calls they make are what produce the text. Without them, the text that code builds never arrives.
Should I block CSS when scraping text with Playwright?
Usually not. innerText is aware of how text is rendered and leaves out hidden elements. Without the stylesheets, elements that CSS would hide are no longer hidden, so menus, dialogs and similar text can show up in what you read.
Sources
- Network (Playwright docs) (Documentation)
- Page, including page.route (Playwright docs) (Documentation)
- Request.resourceType (Playwright docs) (Documentation)
- Route.abort error codes (Playwright docs) (Documentation)
- HTMLElement.innerText (MDN) (Documentation)