diff --git a/README.md b/README.md index d1304da..c9cba38 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,25 @@ const css_sources = await scrape_css(page, 'https://projectwallace.com') await browser.close() ``` +`scrape_css` rejects when the navigation fails (DNS error, timeout, ...), so a failed scrape can be told apart from a page without CSS. It accepts `waitUntil` and `timeout`, which are passed to `page.goto()`. + +### Errors while collecting + +A frame or stylesheet body that cannot be read (a detached frame, a response body the browser already dropped) is skipped, so the rest of the page is still collected. Pass `on_error` to `scrape_css` or `collect_css` to find out about it: + +```js +const css_sources = await collect_css(page, css_responses, { + on_error({ source, url, error }) { + // source is 'frame' or 'response' + console.warn(`Skipped ${source} ${url}`, error) + }, +}) +``` + +### Stylesheets without a recorded response + +A `` stylesheet that loaded, but has no response recorded by `track_css_responses` (it came from the cache or a service worker, or tracking started late), is fetched again from the page, as long as it is served as `text/css` and readable from the page. `@import`ed stylesheets cannot be recovered this way. + ## Design principles - Scrape every stylesheet the page declares, regardless of whether its conditions currently apply. A `` is scraped even when the user prefers a light color scheme, because the browser downloads it anyway and the page's full CSS is what we want. diff --git a/src/browser.ts b/src/browser.ts new file mode 100644 index 0000000..8d06e4a --- /dev/null +++ b/src/browser.ts @@ -0,0 +1,135 @@ +// Functions in this file run inside the browser, via `frame.evaluate()`. Playwright serializes +// them with `toString()`, so each one must be fully self-contained: no imports, no references to +// anything outside its own body. They are excluded from Node coverage (see vitest.config.ts) +// because v8 coverage in the Node process cannot see them; the integration tests exercise them. + +/** What `read_page_css` finds in a frame. */ +export type CSSWalkEntry = + | { + type: 'link' + href: string + /** Normalized: lowercased, whitespace collapsed, e.g. `stylesheet alternate`. */ + rel: string + disabled?: string + /** The stylesheet text, only for a loaded link that had no recorded network response + * (cache hit, service worker, late tracking), obtained by fetching it again. */ + fetched_css?: string + } + | { type: 'inline'; css: string } + | { type: 'adopted'; css: string } + | { type: 'style'; css: string } + | { type: 'cssom'; css: string } + +/** Walks a frame's document and every nested open shadow root exactly once, in document order, + * and reports each ``, each non-empty `