Skip to content

Writing browser Implementations

Open the browser inside the stream, wait for content, decode what the page returns and never report a half-loaded page as a result.

A browser Implementation has the same shape as an HTTP one: take the input, read the source, emit items. What differs is that a page is a moving target. It renders late, loads more on scroll and hides failures behind a normal-looking screen.

Open inside the stream ​

Open the page inside the handler, never while the Layer is built.

Example (QuotesBrowserLive from Adding a browser opens a page per Run, shortened)

ts
export const QuotesBrowserLive = Scraper.layer(Quotes, ({ maxPages }) =>
  Stream.unwrap(
    Effect.gen(function* openPage() {
      const page = yield* Browser.open({ timeout: "15 seconds" });

      // …return a Stream that reads page after page
    })
  )
);

Browser.open() needs a Scope. A handler that returns an Effect gets the Run's, so the page and its browser close when the Run ends, fails or is interrupted. A handler that returns a Stream opens the page inside Stream.unwrap, which uses the Stream's own scope.

Opening a page while the Layer is built would start a browser for every deployment and never close it.

Check the navigation status ​

page.goto returns the HTTP status and accepts any. When the status decides the outcome, open the page with navigate, which fails with a Shared error unless it is 2xx.

ts
yield* navigate(page, url, "Quotes");

A 403 becomes Blocked and a 429 RateLimited, the same as for an HTTP Scraper.

Wait for content, not for load ​

A page that finished loading may not have rendered its data. Wait for the thing you came for, and include the explicit "nothing here" state, so an empty result is told apart from a page that never rendered.

QuotesBrowserLive waits for the first quote and turns a timeout into SchemaDrift:

ts
yield* page
  .waitFor(() => document.querySelector(".quote") !== null)
  .pipe(
    Effect.mapError(
      () =>
        new SchemaDrift({
          reason: "The page rendered no quotes",
          sample: url,
        })
    )
  );

For a source with an explicit empty state, wait for a predicate that is true for either the rows or that state.

Decide what a timeout means for this source and map it:

The wait timed out becauseFail with
The site showed a login or a challenge insteadBlocked
The layout changed and the selector no longer matchesSchemaDrift
The site never answeredUpstreamDown

Every page operation, waits included, is bounded by the timeout the page was opened with, so no single step can hang the Run: Browser.open({ timeout: "15 seconds" }).

Open before load ​

goto and navigate wait for the page's load event, which fires after every image, script, ad and tracker on the page has loaded. On a page with dozens of third-party subresources that can take longer than the page's timeout, while the data you need rendered long before. For such a source, pass { waitUntil: "domcontentloaded" }, which returns once the HTML is parsed:

ts
yield* navigate(page, url, "Quotes", { waitUntil: "domcontentloaded" });

The page is then still loading, so the Implementation must wait for everything it touches itself: waitFor the rows or the explicit empty state, and handle anything that appears late, such as a consent banner a script inserts after a few seconds. A banner that appears after the Implementation checked for it covers the page and makes every later click time out. Keep the default when the source works with it.

Read with evaluate, then decode ​

page.evaluate runs a function inside the page and returns its result. Collect plain data there and do the real parsing in your own code.

ts
const rows = yield* page
  .evaluate(() =>
    [...document.querySelectorAll(".quote")].map((quote) => ({
      author: quote.querySelector(".author")?.textContent ?? "",
      text: quote.querySelector(".text")?.textContent ?? "",
    }))
  )
  .pipe(decodeScrapedRecord(Schema.Array(Row)));

Two rules:

  • The function is serialized. It cannot use variables or helpers from your module. Define what it needs inside it, or pass values as the second argument.
  • Its result is unchecked. Run it through decodeScrapedRecord, so a changed page fails with SchemaDrift and a sample.

Refuse a truncated result ​

Pages that load more on click or scroll are the main source of silent data loss. A browser Implementation must be able to say "I did not see everything".

  • Bound every loop. Give "load more" and "next page" a maximum number of steps. Reaching the bound with more to load is a failure, not a result.
  • Detect a stall. After each click, wait until the page actually changed. If it did not, fail. clickUntilChanged does both steps.
  • Detect a cycle. If a step shows a window you have already seen, stop with a failure.

When the loop reaches its bound with more left to load, fail with SchemaDrift and say how far it got:

ts
new SchemaDrift({
  reason: "Load-more limit reached before the full result was loaded",
  sample: `${rows} rows after ${limit} clicks`,
});

When a click loads nothing, clickUntilChanged fails with the error its onStall returns.

A click that fails is not a stall. It stays a BrowserError and reaches the catch at the outside.

A caller can raise the limit through the input. A caller cannot recover rows it never knew were missing.

Map BrowserError ​

BrowserError is not a declared error, so it must not escape the handler. Catch it once, at the outside of the browser step.

ts
Stream.catchTag("BrowserError", ({ operation, reason }) =>
  Stream.fail(
    new UpstreamDown({
      reason: `Browser ${operation} failed: ${reason}`,
    })
  )
)

Map the specific waits first, as above, and let this catch the rest.

Cookie banners cover the controls you need to click. Dismiss them through the site's own visible "reject" button when it is present, and continue when it is not. Do not accept optional cookies on a caller's behalf.

Emit when you are sure ​

An HTTP Scraper can emit page by page. A browser Scraper that merges overlapping windows often cannot, because a later window may correct an earlier row. Such a Scraper collects all windows, merges them by key and emits once the traversal has ended.

Choose deliberately: emit early when rows are final, emit at the end when later observations can change them.

Test in a real browser ​

Browser tests run a real Chromium, nodeBrowser, against HTML the test serves through Playwright's route. They cover what a unit test cannot: late rendering, stalls, cycles and the step limit. Keep the pages a test serves in test/fixtures/, apart from the test code. See Adding a browser for a small harness and Testing a browser scraper for recorded pages, countries and keeping paid sessions out of tests.

Source ​

  • browser.ts: Page, navigate and clickUntilChanged
  • node.ts: nodeBrowser, which the test harness uses