@tinybrowser/wasm
v0.0.17
Published
A tiny web browser as a WebAssembly component. Embed it in Workers, Node, Bun, or a web page.
Readme
@tinybrowser/wasm
An explicit JavaScript driver for the tinybrowser:[email protected] WebAssembly
component. The driver fetches, compiles, and instantiates nothing until you ask
for it, and it takes every input as a value you pass in.
Part of tinybrowser. See https://tinybrowser.ericc.ch for the project and its live demo.
Install
npm install @tinybrowser/wasm
# or
bun add @tinybrowser/wasmThe package ships the transpiled JavaScript glue, the component, and its core modules. When the Rust component changes, rebuild them from this repository:
cargo build -p tinybrowser-wasm --target wasm32-wasip2 --release
bun install
cd packages/wasm
bun run buildbun run build transpiles with
jco, optionally optimizes the
component with wasm-opt, and compiles the TypeScript sources into dist/.
Set WASM_OPT_LEVEL=0 to skip wasm-opt. Set TINYBROWSER_WASM_PATH to point
at a different component.
Why so much setup
The driver has no hidden module singleton and no runtime environment detection. You supply:
instantiate: the component's generatedinstantiatefunction.module: a function that returns aWebAssembly.Modulefor each core module the generated glue asks for.transport: how the engine performs HTTP.wasi: the WASI imports the component needs.
This keeps bundler behavior predictable and lets one process host multiple independent browsers.
Node
import { createTinyBrowser } from "@tinybrowser/wasm";
import { instantiate } from "@tinybrowser/wasm/instantiate";
import {
createNodeModuleLoader,
createNodeTransport,
createNodeWasi,
} from "@tinybrowser/wasm/node";
const browser = await createTinyBrowser({
instantiate,
module: createNodeModuleLoader(
import.meta.resolve("@tinybrowser/wasm/core.wasm"),
),
wasi: createNodeWasi({
onStdout: (text) => console.log("[tinybrowser]", text),
onStderr: (text) => console.error("[tinybrowser]", text),
}),
transport: createNodeTransport(),
});
const context = browser.createContext({ userAgent: "my-agent/1.0" });
const tab = context.openTab();
const result = await tab.goto("https://example.com/", {
waitUntil: "load",
timeoutMs: 20_000,
});
console.log(result.reason, tab.title(), tab.url());
browser.dispose();createNodeTransport uses global fetch. To inject another implementation,
pass { fetch }. Keep the directory containing core.wasm intact. The glue
also loads two small companion modules from the same directory.
Browser
Browsers cannot call cross-origin HTTP directly. Use the hop proxy in the
website (apps/website/src/pages/api/hop.ts) and let the proxy enforce its own
allow-list.
import { createTinyBrowser } from "@tinybrowser/wasm";
import { instantiate } from "@tinybrowser/wasm/instantiate";
import {
createBrowserModuleLoader,
createBrowserWasi,
createProxyTransport,
} from "@tinybrowser/wasm/browser";
const browser = await createTinyBrowser({
instantiate,
module: createBrowserModuleLoader({
baseUrl: new URL("/wasm/", location.href),
fetch,
}),
wasi: createBrowserWasi(),
transport: createProxyTransport({
endpoint: "/api/hop",
fetch,
}),
});
const tab = browser.createContext().openTab();
await tab.goto("https://example.com/");Copy the contents of dist/wasm/ to the baseUrl you pass. Both loaders are
explicit about fetching, so you choose the cache headers and the asset layout.
Workers
import coreWasm from "@tinybrowser/wasm/core.wasm";
import core2Wasm from "@tinybrowser/wasm/core2.wasm";
import core3Wasm from "@tinybrowser/wasm/core3.wasm";
import { instantiate } from "@tinybrowser/wasm/instantiate";
import {
createWorkersModules,
createWorkersTransport,
createWorkersWasi,
instantiateWorkers,
} from "@tinybrowser/wasm/workers";
export default {
async fetch(request, env) {
const browser = await instantiateWorkers({
instantiate,
modules: createWorkersModules({
core: coreWasm,
core2: core2Wasm,
core3: core3Wasm,
}),
wasi: createWorkersWasi({ onStdout: (text) => console.log(text) }),
transport: createWorkersTransport({ fetch }),
});
const tab = browser
.createContext()
.openTab();
await tab.goto("https://example.com/");
const title = tab.title();
browser.dispose();
return new Response(title);
},
};createWorkersModules maps the three imported modules onto the filenames the
generated glue asks for (CORE_MODULE_NAMES), so callers never type
"tinybrowser.core2.wasm" by hand. The .wasm subpath imports ship their own
WebAssembly.Module declarations, so moduleResolution: nodenext projects
typecheck without a global *.wasm shim.
In workerd, call instantiateWorkers() lazily inside a request handler, not
at module scope. workerd forbids crypto.getRandomValues during global
evaluation, and the WASI shim may use it while instantiating.
createWorkersModuleLoader(coreModule, auxModules) is available when you want
to build createTinyBrowser yourself. Workers have no filesystem, so you supply
every module as an already-compiled WebAssembly.Module.
State
Storage and history are plain JSON-serializable values. Persist them wherever
you like. The driver never writes to disk or localStorage on its own.
const context = browser.createContext({ storageState });
const tab = context.openTab();
await tab.restoreTabState(tabState);
// Later:
const nextStorage = context.exportStorageState();
const nextTab = tab.exportTabState();storageState matches the Playwright shape: cookies, origins, and an
optional indexedDB. Cookies use Unix seconds and expires: -1 for session
cookies. A leading dot in domain encodes a domain cookie. hostOnly is
included in exported cookies. sameSite: "Default" is preserved through the
sameSiteRaw field.
Web Storage keys and values are ordinary JavaScript strings in both directions.
The engine stores them DOMString-encoded so lone UTF-16 surrogates survive the
trip through Rust. encodeDomString and decodeDomString do that conversion,
and localStorage() and sessionStorage() decode before returning. The driver
stores indexedDB entries verbatim.
Both parseStorageState and parseTabState validate unknown input and throw
StateConversionError with the exact failing path.
Navigation
goto, mount, back, forward, reload, and restoreTabState return a
NavigationResult:
interface NavigationResult {
ok: boolean;
reason:
| "load"
| "domcontentloaded"
| "networkidle"
| "quiet"
| "timeout"
| "aborted"
| "step-cap"
| "navigation-failed";
url: string;
steps: number;
idleSteps: number;
elapsedMs: number;
error?: string;
status?: number;
headers?: FetchHeader[];
}A network navigation fills status and headers from the response it mounted.
tab.lastResponse() returns the same metadata as { url, status, headers }, or
null when the current document was mounted locally.
ok is true only when the driver reached the requested waitUntil condition.
It is false for timeout, aborted, step-cap, and navigation-failed. A
timeout or an AbortSignal stops waiting without touching the page's
in-flight fetch() calls
(https://fetch.spec.whatwg.org/#fetch-method). A new navigation replaces the
previous navigation and aborts the old document's requests, and
tab.stopLoading() or disposing the tab stops its requests explicitly.
waitForIdle pumps the event loop without issuing a new navigation.
reload refetches or remounts the current history entry without changing
history. restoreTabState imports a TabState and then calls reload on it.
The restored tab then shows the saved page, and history does not grow by one
entry. restoreTabState defaults to quiet rather than load: a resumed
context is disposed by its caller, so the restore waits for the page's own
post-load boot, including a boot request's timeout, before it returns. Pass
waitUntil: "load" to stop at the load event instead.
Lower-level controls are available when the high-level pump does not fit:
tab.step(), tab.raw, tab.dispatchInput(), tab.lastResponse(),
tab.addInitScript(), tab.setViewport(), tab.eval(), and
tab.evalBounded(source, timeoutMs).
addInitScript(script) runs script before every document the context or tab
mounts. A tab runs the context scripts first, then its own scripts, then the
document's own scripts.
setViewport(width, height) keeps the size for later documents. The tab applies
the stored viewport to every mount until the next call changes it.
setDeviceScaleFactor(value) sets the tab's device pixels per CSS pixel. It
must be a positive finite number and defaults to 1. The factor drives
window.devicePixelRatio, resolution media queries, and srcset density
selection. render() and screenshot() output is scaled by it and rounded to
device pixels; screenshot clips stay in CSS pixels.
dispatchInput accepts pointer-move, pointer-down, pointer-up,
double-click, wheel, key-down, key-up, and insert-text. A
double-click sends a full click sequence with clickCount 1 and 2, so dblclick
handlers fire.
Playwright-shaped API
@tinybrowser/wasm/playwright wraps an explicit TinyBrowser with
createPlaywright(browser). The subpath imports no node:* modules, so the same
code runs in browsers, Cloudflare Workers, Deno, Bun, and Node.
import { createPlaywright } from "@tinybrowser/wasm/playwright";
const playwright = createPlaywright(browser);
const context = await playwright.newContext({ storageState });
const page = await context.newPage();
const response = await page.goto("https://example.com/");
console.log(response.status());
await page.getByLabel("Email").fill("[email protected]");
await page.getByRole("button", { name: "Sign in" }).click();
const png: Uint8Array = await page.screenshot();
const state = await context.storageState();
await context.close();The facade covers browser, context, and page lifecycle, storageState, and
navigation. newContext() and newPage() accept Playwright's
deviceScaleFactor option alongside viewport. goto, reload, goBack, and
goForward return a Response with the real HTTP status and headers when the
target came from the network. setContent mounts local HTML without a network
response.
addInitScript runs on the context or the page. Locators are lazy, auto-waiting,
and strict by default. They support locator, getByRole, getByText,
getByLabel, getByPlaceholder, getByTestId, getByAltText, and getByTitle,
plus css=, text=, role=, nth=, and >> selectors, chaining, and
filtering. evaluate accepts a synchronous or asynchronous callback. keyboard
and mouse send trusted input, including dblclick and Playwright key chords.
screenshot() returns a PNG in a Uint8Array.
The facade drives the main frame only. It does not provide @playwright/test,
traces, or page.route(). To intercept hops, use createFetchTransport. The
engine embeds a 5.2 KiB Basic Latin sans-serif fallback font so layout, locator
clicks, and ASCII screenshots work without passing fonts; any font registered
through fonts or loadFonts takes priority ahead of it. Pass WOFF2 subsets
the host can decode. loadFonts runs once, before the first render() or
screenshot(); text laid out before that uses the fallback metrics, so pass
fonts when layout must match the first paint. A host whose bundler cannot
import font files can embed the bytes as base64 text and decode them, as
apps/executor/fonts.ts does. If you run the native binary,
connect the official playwright-core over CDP instead.
Each facade object exposes .raw for the driver below it: browser.raw is the
TinyBrowser, context.raw is the BrowserContext, and page.raw is the
BrowserTab.
Fetch transports
createFetchTransport maps the component's fetch requests onto fetch. The
transport:
- forces
redirect: "manual"andcache: "no-store" - strips
host,connection,content-length,transfer-encoding,keep-alive,upgrade, and optionallycf-*headers - strips
content-encodingandcontent-lengthfrom responses, and keepsSet-Cookielines separate - enforces
maxBodyBytesby cancelling the response stream - maps failures to
dns,connect,tls,timeout,limit,queue-full, orcancelled
onHopStart and onHopSettled receive each exchange for logging or metrics.
validateUrl is the last chance to reject a URL before any network call.
createProxyTransport posts one JSON hop request to your endpoint and decodes
the binary frame response from apps/website/src/pages/api/hop.ts. It expects
application/octet-stream and maps framed error metadata back to the
component's error variants. The frame code lives in
packages/wasm/src/hop-wire.ts, and the website re-exports it from
apps/website/src/lib/hop-wire.ts.
Exports
| Entry | Contents |
| --- | --- |
| @tinybrowser/wasm | driver, state conversion, transports, WASI shim |
| @tinybrowser/wasm/playwright | Playwright-shaped browser, context, page, and locator facade over TinyBrowser |
| @tinybrowser/wasm/workers | Workers module source helpers |
| @tinybrowser/wasm/node | Node module loading and fetch transport |
| @tinybrowser/wasm/browser | browser module loading and hop proxy |
| @tinybrowser/wasm/wasi | WASI shim and asset URLs |
| @tinybrowser/wasm/instantiate | generated instantiate function |
| @tinybrowser/wasm/core.wasm | main core Wasm module |
| @tinybrowser/wasm/core2.wasm, core3.wasm | small companion core modules |
| @tinybrowser/wasm/component.wasm | original component |
The core API is intentionally verbose. A convenience helper that would hide a fetch, a global, or a choice about the environment does not belong there. The Playwright subpath is opt-in, and it wraps the browser you built.
Source pointers
| Need | Source |
| --- | --- |
| Full WIT contract (resources, types, host imports) | crates/wasm/wit/browser.wit |
| Navigation pump, waitUntil modes, and wakeups | packages/wasm/src/driver.ts |
| Playwright-shaped API | packages/wasm/src/playwright.ts |
| Locator parsing, strict mode, and auto-waiting | packages/wasm/src/playwright-selectors.ts |
| Public TypeScript types and raw WIT bindings | packages/wasm/src/types.ts |
| Fetch, proxy, and host-bridge transports | packages/wasm/src/transport.ts |
| Minimal WASI shims | packages/wasm/src/wasi.ts |
| Full project documentation and live demo | tinybrowser.ericc.ch/#documentation |
License and credits
MIT. See LICENSE, NOTICE, and CREDITS.md. The source lives at tinybrowser-dev/tinybrowser, and the project site is https://tinybrowser.ericc.ch.
