new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · Runtime · all subjects

bun apis/headless browser

38 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Bun.WebView headless browser API

Bun provides Bun.WebView for headless browser functionality.

Bun.WebView overview

Bun.WebView is a headless browser built into the runtime for loading pages, running JavaScript inside them, simulating user input, and capturing screenshots without external dependencies like Puppeteer or Playwright. On macOS it uses the system's WKWebView with zero dependencies. On Linux and Windows it drives Chrome, Chromium, Edge, or Brave over the Chrome DevTools Protocol. All input methods dispatch native browser events, so pages see isTrusted: true. This API is experimental and may change in future releases.

Bun.WebView constructor options

new Bun.WebView(options?) accepts: width (number, 1-16384, default 800), height (number, 1-16384, default 600), url (string, optional to start navigating immediately), headless (boolean, only true is implemented), backend ("webkit" | "chrome" | object, defaults to "webkit" on macOS and "chrome" elsewhere), console (typeof console | function to capture page-side console calls), dataStore ("ephemeral" | { directory: string }, defaults to "ephemeral" for in-memory storage). The constructor is synchronous and returns immediately while spawning the browser subprocess in the background.

Bun.WebView automatic cleanup with using

Bun.WebView implements Symbol.dispose and Symbol.asyncDispose, so you can use 'using' or 'await using' to automatically close the view when it goes out of scope. Example: { await using view = new Bun.WebView(); await view.navigate("https://example.com"); } // view.close() called automatically.

Bun.WebView persistent storage

By default each view uses ephemeral in-memory storage where cookies, localStorage, IndexedDB, and cache are discarded when the view closes. To persist state pass dataStore: { directory: "./browser-profile" }. Views that share the same directory share cookies and storage. With Chrome backend, dataStore.directory maps to --user-data-dir and applies to the entire Chrome process, not per-view, so the first view's directory wins for all subsequent views. With WebKit backend, persistent storage requires macOS 15.2+; on older versions use dataStore: "ephemeral" (the default).

Bun.WebView backends table

Backend comparison: webkit (WKWebView, macOS only, no requirements—uses system WebKit.framework) vs chrome (Blink, macOS/Linux, requires Chrome/Chromium/Edge/Brave installed or Playwright's chrome-headless-shell). On macOS the default is webkit; elsewhere it's chrome. Requesting backend: "webkit" on non-macOS throws.

WebKit backend subprocess communication

Bun spawns a lightweight host subprocess (the bun binary re-executed in a special mode) that owns the WKWebView on its main thread. Your Bun process talks to it over a Unix socket using a compact binary protocol. The host process is spawned once and shared by every webkit view in your program.

Chrome backend subprocess communication

Bun either connects to an already-running Chrome over a WebSocket or spawns a headless Chrome subprocess and talks to it over a pipe (--remote-debugging-pipe). Communication uses the Chrome DevTools Protocol. Chrome is spawned (or connected) once per Bun process. Each new Bun.WebView({ backend: "chrome" }) creates a new tab with Target.createTarget in that single Chrome instance.

Chrome executable search order

When Bun needs to spawn Chrome, it searches in this order: 1) The path you passed in backend: { type: "chrome", path: "..." } 2) The BUN_CHROME_PATH environment variable 3) $PATH (google-chrome-stable, google-chrome, chromium-browser, chromium, brave-browser, microsoft-edge, chrome) 4) Standard install locations (/Applications/Google Chrome.app, ~/Applications/..., /usr/bin/..., /snap/bin/...) 5) Playwright's cache (~/Library/Caches/ms-playwright or ~/.cache/ms-playwright) for chrome-headless-shell. If none is found, the constructor throws.

Chrome backend auto-connect to existing browser

By default, before spawning, Bun checks whether a Chrome-family browser is already running with remote debugging enabled by reading the DevToolsActivePort file from standard profile directories. If found, Bun connects to that browser over WebSocket instead of spawning a new one—your views open as tabs in your existing browser. To enable remote debugging in running Chrome, visit chrome://inspect/#remote-debugging and flip the toggle, or launch Chrome with --remote-debugging-port=9222. Chrome prompts for permission on each new connection when using the chrome://inspect toggle.

Chrome backend connection control

To control auto-connect behavior explicitly, use the object form of backend. new Bun.WebView({ backend: { type: "chrome", url: false } }) always spawns a fresh headless Chrome and never auto-connects. new Bun.WebView({ backend: { type: "chrome", url: "ws://127.0.0.1:9222/devtools/browser/abc123..." } }) connects to a specific DevTools WebSocket URL. If auto-detect finds a stale DevToolsActivePort file, the WebSocket connect fails and Bun transparently falls back to spawning its own Chrome. An explicit url: "ws://..." does not fall back—a failed connection throws. Passing path or argv implies spawn mode and skips auto-detect; url: "ws://..." cannot be combined with path or argv.

Chrome backend launch flags

When spawning Chrome, Bun passes these default flags: --user-data-dir=<temp> --remote-debugging-pipe --headless --no-first-run --no-default-browser-check --disable-gpu --disable-extensions --disable-background-networking --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-renderer-backgrounding --disable-ipc-flooding-protection --no-startup-window. Append your own with argv—Chrome resolves duplicate switches last-wins, so you can override any default.

Chrome subprocess output control

Browser subprocess stdout/stderr are silenced by default. Chrome is noisy on stderr (font-config warnings, GCM registration, updater checks). To see it, pass "inherit" to stdout or stderr in the backend object: new Bun.WebView({ backend: { type: "chrome", stderr: "inherit", stdout: "inherit" } }). The webkit backend accepts the same stdout/stderr options.

Bun.WebView navigate method

navigate(url) loads a URL and resolves when the main frame's load event fires. After it resolves, view.url and view.title reflect the new page, and view.loading is false. Supported URL schemes: https://, http://, data:text/html,<content>, file:///path. If navigation fails (DNS failure, connection refused, invalid URL), the promise rejects with an Error. Only one navigation may be in flight per view at a time; calling navigate() while another is pending throws ERR_INVALID_STATE synchronously.

Bun.WebView history navigation

goBack() works like the browser's back button. goForward() works like the browser's forward button. reload() reloads the current page. Calling goBack() at the beginning of history (or goForward() at the end) resolves undefined without navigating—it doesn't reject.

Bun.WebView navigation callbacks

Set onNavigated and onNavigationFailed callbacks to observe every navigation including ones triggered by the page itself (link clicks, location.href = ..., redirects) and by reload()/goBack()/goForward(). onNavigated callback: (url: string, title: string) => void, fires after each successful navigation. onNavigationFailed callback: (error: Error) => void, fires after each failed navigation. These fire before the corresponding navigate() promise settles. Set to null to remove.

Bun.WebView evaluate method

evaluate(script) runs an expression in the page's main frame and gets its result back as a native JavaScript value. The script is wrapped as await (<your script>), so it must be an expression, not a statement sequence. If it evaluates to a Promise, the promise is awaited and its resolved value is returned. The result round-trips through JSON.stringify in the page and JSON.parse in Bun. Arrays and plain objects come back as real structures; undefined, functions, and symbols resolve to undefined; circular references reject. If the script throws (or returns a rejected promise), evaluate() rejects with an Error whose message comes from the page-side exception. Only one evaluate() may be in flight per view at a time; a second concurrent call throws ERR_INVALID_STATE.

Bun.WebView screenshot method

screenshot(options?) captures the current viewport as an image. Format options: format: "png" (lossless, default), format: "jpeg" with quality 0-100 (default 80), format: "webp" with quality (Chrome backend only). Quality is ignored for PNG. Encoding option controls return type: "blob" (default, MIME type set automatically, zero-copy mmap-backed on WebKit, works with Bun.write() and new Response()), "buffer" (Node Buffer, zero-copy mmap-backed on WebKit), "base64" (string, zero-decode on Chrome), "shmem" ({ name: string, size: number } POSIX shared-memory segment name, not supported on Windows).

Bun.WebView screenshot shared memory for terminal graphics

encoding: "shmem" is designed for Kitty's terminal graphics protocol t=s transmission mode. Bun writes the image to a POSIX shared-memory segment and returns its name; the terminal reads it directly and unlinks it when done. On WebKit, the shm name looks like /bun-webview-<pid>-<seq>; on Chrome, /bun-chrome-<pid>-<seq>. If you request "shmem" and don't hand the name to something that will shm_unlink it, the segment leaks until your process exits.

Bun.WebView click by coordinates

click(x, y, options?) clicks at viewport coordinates. The promise resolves after the page has processed the full mousedown → mouseup → click sequence, including any JavaScript handlers. No polling needed. Options: button ("left" | "right" | "middle", default "left"), modifiers (array of "Shift" | "Control" | "Alt" | "Meta"), clickCount (1 | 2 | 3, default 1 for single/double/triple-click).

Bun.WebView click by selector

click(selector, options?) passes a CSS selector and Bun waits for the element to become actionable, then clicks its center. An element is actionable when it: exists in the DOM, has a non-zero bounding box, is inside the viewport, has been stable (bounding box unchanged) for two consecutive animation frames, is the topmost element at its center point (not covered by an overlay). The check runs page-side at requestAnimationFrame rate. If the element never becomes actionable within timeout milliseconds (default 30000), the promise rejects. The selector is passed as data, not interpolated into a script, so selectors containing quotes or JavaScript syntax are safe.

Bun.WebView type method

type(text) inserts text into the currently focused element. It uses the browser's InsertText editing command (the same path as paste), not per-character keystrokes. It fires beforeinput/input events with isTrusted: true, but no keydown/keyup events. There's no IME processing and no smart-quote substitution—the text lands exactly as given.

Bun.WebView press method

press(key, options?) presses a named virtual key or single-character chord. Named virtual keys: Enter, Tab, Space, Backspace, Delete, Escape, ArrowLeft, ArrowRight, ArrowUp, ArrowDown, Home, End, PageUp, PageDown. Any single character combined with modifiers sends a keyboard chord. Modifier names: "Shift", "Control" (or "Ctrl"), "Alt" (or "Option"), "Meta" (or "Cmd" / "Command"). On WebKit, most named keys without modifiers map to editing commands and resolve after the page applies them. Escape, Space, and any key with modifiers fall back to raw keydown/keyup events; follow with evaluate() if you need to observe the effect.

Bun.WebView scroll method

scroll(dx, dy) scrolls by a pixel delta and fires a native wheel event at the viewport center. dx and dy must be finite. Positive dy scrolls down (content moves up), matching window.scrollBy. If a scrollable element sits under the viewport center, it receives the wheel event instead of the document.

Bun.WebView scrollTo method

scrollTo(selector, options?) scrolls an element into view by CSS selector. Options: block ("start" | "center" | "end" | "nearest", default "center" for vertical alignment), timeout (number, default 30000 milliseconds to wait). scrollTo() waits at requestAnimationFrame rate for the element to exist, then calls element.scrollIntoView({ block, behavior: "instant" }). It scrolls every scrollable ancestor, not just the document.

Bun.WebView resize method

resize(width, height) changes the viewport size. Width and height must each be between 1 and 16384.

Bun.WebView console capture overview

Forward console.* calls from the page to your Bun process by passing the console option to the constructor. Two approaches: pass globalThis.console (the actual object by reference) and page-side console.log("hi") prints to stdout with Bun's formatter; console.error goes to stderr. Or pass a function to receive each call yourself: (type, ...args) => { /* type is "log" | "warn" | "error" | "info" | "debug" | ... */ }. If you don't pass console, page-side console output is dropped.

Bun.WebView console capture argument serialization

Primitive arguments (strings, numbers, booleans, null, undefined) unwrap to their raw values. Object arguments arrive as a serialized descriptor: Chrome backend returns the raw CDP RemoteObject (object with type, className, description, and when available a preview.properties array); WebKit backend returns the JSON.stringify round-trip of the object (functions, circular references, and other non-serializable values fall back to their String(...) coercion). Ordering guarantee: a console.log(...) inside a script passed to evaluate() reaches your handler before that evaluate() resolves, as both travel over the same IPC connection.

Bun.WebView raw Chrome DevTools Protocol

When using backend: "chrome", you can drop down to raw CDP commands for anything the high-level API doesn't cover. Call cdp(method, params?) which returns the result object from the CDP response. If Chrome returns an error (unknown method, bad params), the promise rejects with its error.message. Commands are scoped to this view's session (they target this tab). You must await navigate(...) at least once before calling cdp()—the first navigation establishes the session. Calling cdp() before that throws ERR_INVALID_STATE. params must be a JSON-serializable object; omit it for commands that take no parameters. One cdp() call may be in flight at a time per view.

Bun.WebView Chrome DevTools Protocol events

Bun.WebView extends EventTarget. With the Chrome backend, CDP events are dispatched as DOM events whose type is the CDP method name and whose data is the parsed params object. Example: view.addEventListener("Network.responseReceived", event => { console.log(event.data.response.status, event.data.response.url); }). Events for which no listener is registered are dropped before JSON params are even parsed, so enabling a chatty domain (like Network) is cheap if you only listen for one or two event types. On the WebKit backend, cdp() throws ERR_METHOD_NOT_IMPLEMENTED—there is no DevTools Protocol bridge. The EventTarget interface still works for your own dispatchEvent() calls.

Bun.WebView close method

close() destroys the page's renderer process, rejects any pending promises on the view with Error("WebView closed"), and makes every subsequent method call throw ERR_INVALID_STATE. Closing is synchronous and idempotent. view[Symbol.dispose] and view[Symbol.asyncDispose] both point to close(), so using / await using work.

Bun.WebView.closeAll static method

Bun.WebView.closeAll() force-kills (SIGKILL) both the Chrome subprocess and the WebKit host subprocess. Pending promises on every view reject on the next event-loop tick. Subsequent new Bun.WebView() calls respawn as needed. Bun calls this automatically at process exit, so browser subprocesses never outlive your script.

Bun.WebView event-loop behavior

The browser subprocess does not keep Bun's event loop alive on its own. An open WebView keeps the process alive only while it has a pending operation (such as an unsettled navigate() or evaluate()). Once you close() the last view—or the last pending operation settles—Bun exits naturally.

Bun.WebView subprocess death handling

If the browser subprocess dies unexpectedly (crash, OOM-kill, SIGKILL), every pending promise on every view rejects with an error describing how it died ("Chrome killed by signal 9", "WebView host process died"), and further operations on those views throw.

Bun.WebView concurrency model

Each view has a small number of independent operation slots: one navigate() (shared with reload()/goBack()/goForward() on Chrome backend), one evaluate(), one screenshot(), one cdp() (Chrome only), one simple operation (click(), type(), press(), scroll(), scrollTo(), resize() and reload()/goBack()/goForward() on WebKit backend share this slot). Starting a second operation while its slot is occupied throws ERR_INVALID_STATE synchronously—it does not queue. In practice, await each call. Operations on different views are fully independent and run in parallel—each view has its own renderer process.

Bun.WebView instance properties

url (string, readonly): the current URL, updated when a navigation completes, empty string before first navigation. title (string, readonly): the page's <title>, updated when a navigation completes. loading (boolean, readonly): true while a navigation is in flight. onNavigated ((url: string, title: string) => void) | null: fires after each successful navigation, before the navigate() promise resolves. onNavigationFailed ((error: Error) => void) | null: fires after each failed navigation, before the navigate() promise rejects.

Bun.WebView backend object options

The backend option can be an object with: type ("chrome" | "webkit", required), path (string, chrome only, path to Chrome/Chromium executable, forces spawn mode), argv (string[], chrome only, extra launch flags appended after defaults, forces spawn mode), url (string | false, chrome only, ws:// URL of existing Chrome's DevTools endpoint or false to skip auto-detect and always spawn), stdout ("inherit" | "ignore", route subprocess stdout to Bun's, default "ignore"), stderr ("inherit" | "ignore", route subprocess stderr to Bun's, default "ignore").

Bun.WebView complete example

await using view = new Bun.WebView(); await view.navigate("https://example.com"); await view.click("a[href]"); // waits for the link to be clickable const title = await view.evaluate("document.title"); await Bun.write("page.png", await view.screenshot());

Give your agent this brain