Skip to content

Embed STomp in your site

David Reed edited this page Nov 20, 2026 · 2 revisions

This page shows how to build a browser around STomp: tabs, an address bar with suggestions, Back and Forward, titles and icons, popups that open as tabs, a request log and your own error page. Each section teaches one part of the host API. The worked example at the end puts all of it in one HTML page and one module script that you can copy and run.

You need STomp installed and its dist/ served from a directory of your site, plus a Wisp relay. Install into an existing app covers that. The code on this page uses the same-origin StompController, which is the shortest setup. Same-origin mode is for development: a proxied page shares your page's origin, and STomp's hooks are not a security boundary. For anything public, switch to RemoteController as Origin isolation shows. The rest of the code stays the same.

How the parts fit

Your page creates one controller. The controller talks to the service worker and owns the transport. Every tab is a Frame that the controller creates, and every Frame wraps one <iframe>.

The proxied pages report to your page. When a page loads, changes its title, calls pushState or changes its icon, your page gets a navigate event with the real URL, the title and the history state. You never poll and you never read the frame's document. When a page opens a popup, you get an open callback with the URL. When a request finishes, you get a request report with the frame it belongs to.

That gives a browser UI three jobs: keep one Frame per tab, draw the active tab's reports, and turn user input into calls on the active tab's Frame.

Start the controller

import { SearchBuilder, StompController } from '/stomp/controller.mjs';

const directory = '/stomp/';
const registration = await StompController.register(directory);

const controller = new StompController({
	serviceworker: registration,
	transport: {
		module: '/epoxy/index.mjs',
		options: [{ wisp: 'wss://holywisp.fracit.al/' }],
	},
	directory,
	codec: 'xor',
	onOpen(url, frame) {},
	onRequest(info) {},
	errorPage: '/error.html',
});
await controller.wait();

register(directory) registers serviceWorker.js from that directory with the directory as its scope and updateViaCache: 'none', and resolves once the worker is active (30 s at most). The transport descriptor names a module on your origin; the controller imports it in a worker of its own. Transports and Wisp explains descriptors and the pinned epoxy build. With a bundler, import from the package instead: import { SearchBuilder, StompController } from '@sysce/stomp'.

Create frames and call go() after wait() resolves. Every option is listed in Configure STomp.

Add an address bar

SearchBuilder turns what the user typed into a URL. Give it a search URL with %s where the query goes:

const search = new SearchBuilder('https://duckduckgo.com/?q=%s');

search.query(text) does this:

Input Result
Starts with http:// or https:// The input, unchanged
No spaces and a dot (wikipedia.org, node.js), or localhost with an optional port http:// + the input
Anything else (stomp proxy) The template with %s replaced by encodeURIComponent(input)

Two things to know. A bare host gets http://, and Chrome's own address bar tries https:// first, so swap the scheme when the user did not type one. And any text with a dot and no spaces counts as a host: node.js goes to http://node.js, not to a search.

function typed(text) {
	const url = search.query(text.trim());
	return /^[a-z]+:\/\//i.test(text.trim()) ? url : url.replace(/^http:/, 'https:');
}

form.addEventListener('submit', (event) => {
	event.preventDefault();
	activeTab.frame.go(typed(address.value));
	// as a browser does: the page has focus after Enter, not the bar
	activeTab.frame.element.focus();
});

The bar shows the tab's real URL from its navigate reports (next sections). Do not overwrite it while the user is typing in it: skip the update when document.activeElement is the input.

To show suggestions under the bar while the user types, see Suggest as the user types.

Give each tab its own frame

controller.createFrame() creates an <iframe>, sets its sandbox attribute and returns a Frame. You can also pass an <iframe> you made. The frame is yours to place. Put it in the document before you call go(): the controller measures the frame before the first document loads, and an isolated controller looks the frame up among your page's windows.

function openTab(url) {
	const frame = controller.createFrame();
	frame.element.title = 'Proxied page';
	views.append(frame.element);
	const tab = { frame, info: null };
	tabs.push(tab);
	select(tab);
	if (url) frame.go(url);
	return tab;
}

function select(tab) {
	activeTab = tab;
	for (const other of tabs) other.frame.element.hidden = other !== tab;
}

Hide inactive tabs. Do not detach them: an iframe that leaves the document unloads its page, and putting it back loads the page again.

To close a tab, remove its element. There is no method to drop a Frame from the controller, so take it out of controller.frames yourself, or controller.frames keeps every tab you ever opened:

function closeTab(tab) {
	tab.frame.element.remove();
	controller.frames.splice(controller.frames.indexOf(tab.frame), 1);
	tabs.splice(tabs.indexOf(tab), 1);
}

go(url) resolves when the new document has sent its first report, 1 s after the frame's load event for a document that never reports, and after 30 s at most. The first report comes at document start, so do not wait on go() to read the page.

Follow the page with navigate events

Each proxied page reports when it loads, when it calls pushState or replaceState, on popstate and hashchange, when its title changes and when it swaps its icon. The report is a NavigateInfo:

Field What it is
url The real URL the page shows (https://en.wikipedia.org/wiki/Proxy, not the routed /stomp/... address)
title The page's document.title
canGoBack, canGoForward Whether the tab's history has an entry in that direction; null when the browser has no Navigation API
icon The icon the page declared, resolved against its real URL, or null (see Titles and icons)

You can receive it three ways. Use whichever fits your code:

Where Signature
onNavigate option onNavigate(info, frame)
navigate event on the Frame event.detail is the NavigateInfo
navigate event on the controller event.detail is { info, frame }

A per-frame listener is the simplest for tabs, because the tab is in scope:

frame.addEventListener('navigate', (event) => {
	tab.info = event.detail;
	tabButton.textContent = tab.info.title || tab.info.url;
	if (tab === activeTab) showTab();
});

function showTab() {
	const info = activeTab.info;
	if (document.activeElement !== address) address.value = info?.url ?? '';
	document.title = info?.title || 'My browser';
	back.disabled = info?.canGoBack === false;
	forward.disabled = info?.canGoForward === false;
}

The Frame keeps the last values too: frame.url (read from the page itself), frame.title and frame.lastNavigate. A RemoteFrame has url, title, canGoBack and canGoForward as plain fields instead.

Error pages do not report. While one shows, frame.title and frame.lastNavigate still describe the page before it, and frame.url is null. Show your own error page has a way to hear about them.

Suggest as the user types

The omnibox module gives your address bar a dropdown like a browser's: open tabs to switch to, pages your tabs visited, bookmarks, and the search engine's completions. It is in dist/ as the ES module omnibox.mjs (@sysce/stomp/omnibox with a bundler) and as the classic script omnibox.js, whose global is Omnibox, in builds from 4.2.0-nightly.202611200512.g041dc67 on. Proxied pages never load it.

The completions come from controller.suggest(), which asks the engine through the transport. Your server never sees what the user types, and the engine gets the text from the relay's address with no cookies.

Put the input and an empty list in one positioned box:

<form id="toolbar">
	<div class="omnibox">
		<input id="address" placeholder="Search or type a URL" />
		<div id="suggestions"></div>
	</div>
</form>

The module has no CSS. It empties the list while it is closed and puts data-hover on the highlighted row, so this is enough to start:

.omnibox { position: relative; flex: 1; }
#address { width: 100%; }
#suggestions { position: absolute; top: 100%; left: 0; right: 0; z-index: 1; background: Canvas; border: 1px solid GrayText; }
#suggestions:empty { display: none; }
.omnibox-head { padding: 4px 8px; font-size: 12px; opacity: 0.7; }
.omnibox-row { display: flex; align-items: center; gap: 8px; padding: 4px 8px; }
.omnibox-row[data-hover] { background: Highlight; color: HighlightText; }
.omnibox-icon { width: 16px; height: 16px; }
.omnibox-sub { margin-left: 8px; opacity: 0.7; }
.omnibox-hint { margin-left: auto; opacity: 0.7; }

Give each tab an id when you open it (const tab = { id: ++lastTabId, frame, info: null } in openTab()), then attach the box:

import * as Omnibox from '/stomp/omnibox.mjs';

const engine = 'https://duckduckgo.com/?q=%s'; // the template SearchBuilder has
const visits = Omnibox.visitHistory(); // localStorage, key 'omnibox:visits'
const bookmarks = [{ url: 'https://en.wikipedia.org/', title: 'Wikipedia' }];

// every tab but the one on show, as "Switch to tab" rows
const otherTabs = () =>
	tabs
		.filter((tab) => tab !== activeTab && tab.frame.url)
		.map((tab) => ({
			id: tab.id,
			url: tab.frame.url,
			title: tab.frame.title ?? '',
			activate: () => select(tab),
		}));

const box = Omnibox.attachOmnibox({
	input: address,
	list: document.getElementById('suggestions'),
	search: engine,
	toUrl: typed,
	typedOnly: true,
	local: (text) => [
		...Omnibox.tabRows(text, otherTabs()),
		...Omnibox.historyRows(text, visits.visits(), (url) => visits.forget(url)),
		...Omnibox.bookmarkRows(text, bookmarks),
	],
	complete: (text, signal) => controller.suggest(text, { engine, signal }),
	picks: () => ({
		...Omnibox.historyPicks(
			visits.visits(),
			tabs.map((tab) => tab.frame.url).filter(Boolean),
		),
		openTabs: Omnibox.tabRows('', otherTabs()),
	}),
	navigate: (row) => {
		address.value = row.url;
		form.requestSubmit();
	},
});
form.addEventListener('submit', () => box.close());

And keep each page a tab reaches, in openTab():

frame.addEventListener('navigate', (event) => {
	visits.record(tab, { url: event.detail.url, title: event.detail.title });
});

What each part does:

  • local returns the rows your page knows about, scored for the text. It runs on every keystroke, so it reads from memory. tabRows makes "Switch to tab" rows that call your activate(). historyRows ranks the visit history by match, visits and recency; its third argument lets Shift+Delete forget a page. bookmarkRows takes { url, title } objects.
  • complete runs 250 ms after the user stops typing, for 2 characters or more, and only for a search, not for text that reads as an address. A new keystroke aborts the request in flight through signal, and a late answer is dropped.
  • typedOnly: true is for a bar that shows the tab's URL: the list follows what the user types after focusing it, not the URL that was already there.
  • navigate gets a picked row that has a URL. Putting it in the input and submitting the form runs it through the same code as Enter, and the submit listener closes the list.
  • Clicking the empty bar, or pressing ArrowDown in it, shows picks(): recent and frequent sites and the other tabs.
  • record() updates the tab's last visit when the URL is the same, so calling it on every report (the title arrives after the URL) adds one visit per page, not one per report.

The keys work as in Chrome's address bar: the arrows move and wrap around, Enter opens the highlighted row or submits the form when none is, Tab fills the input, Escape closes the list.

Without a module loader, load <script src="/stomp/omnibox.js"></script> and use the Omnibox global in place of the import. With RemoteController the code is the same; the controller frame asks the engine. Leave icon out of record() and the tab rows unless it is a data:image/ URL or a path on your origin: the module drops a site's own icon URL, which your page would load straight from the site. Configure STomp lists every option, and search suggestions the engines.

Titles and icons

The title is info.title. A page that changes document.title reports again, so a tab label that you set from every report stays current.

The icon is info.icon: the page's first <link rel="icon"> or shortcut icon, else its first apple-touch-icon, resolved against the page's real URL. It is null when the page declares none; a browser then tries /favicon.ico on the page's origin.

Do not put info.icon in an <img> on your page. Your page is outside the service worker's scope, so the browser would fetch the icon directly from the site, past the proxy and from the user's own IP address. With cross-origin isolation headers on your page, most icons would not load at all.

Load the icon from inside the proxied page instead, where the service worker answers every request. A pre hook (see Run your code in every page) can hand your page a message port and draw the icon on request:

function iconHook(stomp) {
	const win = stomp.window;
	if (stomp.kind !== 'document' || !stomp.isTop || win.top === win) return;
	// natives, taken before STomp installs its own hooks
	const apply = win.Reflect.apply;
	const bitmap = win.createImageBitmap;
	const Image = win.Image;
	const channel = new win.MessageChannel();
	channel.port1.onmessage = async ({ data: url }) => {
		let picture = null;
		try {
			const image = new Image();
			image.src = url; // routed through the proxy by then
			await image.decode();
			picture = await apply(bitmap, win, [image, { resizeWidth: 32, resizeHeight: 32 }]);
		} catch {}
		channel.port1.postMessage({ url, picture }, picture ? [picture] : []);
	};
	win.top.postMessage({ tinyBrowserIcon: true }, '*', [channel.port2]);
}

const controller = new StompController({
	// ...
	hooks: { init: { pre: { source: `(${iconHook})(stomp);` } } },
});

Your page keeps the port of each tab's current page and sends it info.icon ?? new URL('/favicon.ico', info.url).href after each report. The answer is an ImageBitmap that you draw on a <canvas> in the tab. The worked example has the host side. The demo at https://stomp.fracit.al loads its bookmark icons the same way.

Back, forward and reload

Call What it does Resolves to
frame.back() Steps the tab's history back, nested frames included, as a browser's Back button does false when there is no entry in that direction
frame.forward() The same, forward false when there is no entry
frame.reload() Reloads the page false when there was nothing to reload; otherwise resolves like go()

back() and forward() never walk your page's history or another tab's. Every tab's frame shares your page's joint session history in the browser, and STomp steps only the entries of that frame.

Enable the buttons from the navigate report (canGoBack, canGoForward) or from frame.canGoBack and frame.canGoForward. Each is null when the browser has no Navigation API. Leave the buttons enabled then and use the false from back() to show that there was nothing to go back to.

Keyboard shortcuts that your page listens for do not fire while the focus is in a proxied page, because the key events go to that page's window. To forward the keys you want, use a hook that posts them to top. The demo's KEY_HOOK in demo/public/pm/main.js forwards Alt+Left, Alt+Right and Escape this way.

Turn popups into tabs

Pass onOpen and every popup becomes a call to it: window.open(), a link with target="_blank" or a window name, a middle click and a modifier click.

onOpen(url, frame) {
	openTab(url);
},

The page's window.open() then returns null, as it does when a popup blocker stops it. The open event on the controller carries the same request (event.detail is { url, frame }).

Without onOpen, popups open as real browser windows that show the proxied page with none of your UI around it. With RemoteController and a cross-origin isolated host page, Chrome gives proxied popups no opener and window.open() returns null anyway, so take popups with onOpen in that setup.

Log requests

onRequest(info) is called once per proxied request, after it finished. The same report is also dispatched as a request event on the controller (event.detail). The service worker sends reports only when you pass onRequest, so to use the event alone, pass an empty onRequest.

Field What it is
url, method The real URL and the method
destination iframe for a tab's document, script, style, image, font and so on; fetch for fetch(), XHR and beacons
status The HTTP status; 0 when the request failed
error, kind Why it failed; kind is set when the proxy produced the failure (transport, timeout, routing, blocked, controller)
ms Time in the service worker, from routing to the response headers
cached, revalidated Answered from STomp's HTTP cache, or from the cache after a 304
bytes Content-Length, when known
frame The Frame showing the page the request belongs to, or null
rule The index of the request rule that applied

frame covers everything in the page: its document, nested frames, about:blank and srcdoc children and workers. A request can come before its document said which frame it is in. STomp waits for that, up to 3 s for a document and 1.5 s for what its head loads, so reports can arrive out of order. A document that failed has frame: null, because the error page never says which frame it is in.

Keep one log per tab, keyed by the Frame:

const logs = new Map(); // Frame -> lines

onRequest(info) {
	if (!info.frame) return;
	const lines = logs.get(info.frame) ?? [];
	lines.push(`${info.method} ${info.status || info.kind} ${info.url} ${info.ms} ms`);
	logs.set(info.frame, lines.slice(-200));
},

RequestInfo lists the fields for scripts (rewriteCache, rewriteIn, rewriteBy) and for workers (client, owner).

Show your own error page

When the proxy cannot produce a document (the site is unreachable, it timed out, something blocked it, the routing failed), the service worker answers with a built-in error page. Set errorPage to show yours. It is a URL on your origin, resolved against your page. With RemoteController it is a path on the proxy origin, where the service worker runs.

STomp serves your page under the tab's routed URL, with the failure's HTTP status, never cached, and with this global in its head before your first script runs:

globalThis.stompError = { url, status, error, kind };
kind Cause
transport The transport could not reach the site (DNS, refused, TLS)
timeout The service worker's timeout ran out
routing STomp could not route the request
blocked A request rule, the content blocker or the mixed content check blocked the document
controller The tab's controller is gone (its page was closed) and no other controller can take the URL

Because the page sits at the failed page's address, location.reload() retries it. If an obfuscator renames globals in your deployment, set names.error and read that name instead.

Error pages do not send navigate reports, so your address bar and tab title keep the previous page. Have the error page tell your UI itself. In error.html:

parent.postMessage({ stompError: globalThis.stompError }, '*');

And in your page, match the message to a tab by its window:

addEventListener('message', (event) => {
	const tab = tabs.find((t) => t.frame.element.contentWindow === event.source);
	if (!tab || !event.data?.stompError) return;
	const { url, kind } = event.data.stompError;
	tab.info = { url, title: `Error: ${kind}`, canGoBack: tab.frame.canGoBack, canGoForward: false, icon: null };
	if (tab === activeTab) showTab();
});

examples/error.html is a complete error page.

Run your code in every page

Hooks are your code, run inside every proxied realm: the top document, nested frames, about:blank children, popups, srcdoc frames, and with workers: true dedicated and shared workers too.

hooks: {
	init: {
		pre: { source: 'console.log("before STomp, in", stomp.url)' },
		post: { url: '/hooks/hide-ads.js' },
	},
	workers: false,
},
Phase When it runs
pre Before STomp installs its hooks. The realm's natives are untouched, so this is where you capture them.
post After STomp's hooks are in, before the page's first script. URLs you set here (img.src, fetch()) are routed.

Each phase is { source } (the text) or { url }. A URL is fetched once, when the controller is created, and its text is what travels to the pages. A changed file reaches pages only after your page creates a new controller, which in practice means a reload of your page. RemoteController fetches it from the proxy origin.

The code runs as a function body with one argument, stomp:

Field What it is
url, origin The page's real URL and origin
isTop The outermost proxied document
nested A child of a proxied page (nested frame, about:blank, srcdoc)
kind document, worker or sharedWorker
phase pre or post
names The deployment's helper names
frameId The controller's id (controller.id)
window The realm's real global

Hook code is trusted. It runs with the realm's real globals: in same-origin mode stomp.window.top is your own page. Anything a hook leaves on the window, the page can reach. Keep references in closures and never store top or stomp.window on an object the page can see.

A hook that throws is logged on the realm's console and reported, never thrown at the page. A hook URL that could not be fetched is reported with phase: 'url', and the controller runs without that hook.

Where What you get
onHookError(info, frame) info is { phase, kind, url, message, stack }; frame is the tab, or null for a URL failure. RemoteController passes only info.
hookerror event event.detail is { info, frame }
controller.hookErrors Every report so far (StompController only)

A hook with a wrong shape (a string instead of { source }, both source and url) is a TypeError from the constructor. examples/hooks/hide-ads.js is a post hook that hides ad elements.

Read and change cookies

Proxied sites keep their cookies in STomp's cookie jar in the service worker, not in the browser's. controller.cookies is your page's view of that jar. Proxied pages cannot reach it.

Method What it does
cookies.get(url) The Cookie header value the proxy would send to url
cookies.set(url, setCookie) Applies one Set-Cookie value, or an array of them, as if url had sent them
cookies.list(origin?) Every stored cookie, or those a page of origin would receive
cookies.clear(origin?) Forgets every cookie, or those of origin

list() returns CookieRecord objects: name, value, domain, path, expires (an ISO date, or null for a session cookie), secure, httpOnly, sameSite and hostOnly.

const origin = new URL(activeTab.info.url).origin;
for (const cookie of await controller.cookies.list(origin))
	console.log(`${cookie.name}=${cookie.value}`);

await controller.cookies.set('https://example.com/', 'theme=dark; Path=/; Max-Age=86400');

Calling clear() without an origin also forgets the controller ids your origin keeps, so open tabs get new routed addresses on their next reload. For a "Clear site data" button, clear the site's storage too: controller.forgetStorage(origin) drops its localStorage, sessionStorage, IndexedDB and Cache Storage.

await controller.cookies.clear(origin);
await controller.forgetStorage(origin);
await activeTab.frame.reload();

Handle a deploy

After you deploy a new STomp build, a visitor's page can load the new controller bundle while the old service worker is still in charge, or the other way round. The controller handles this itself. When it finds a worker of another build, it asks the registration to update, waits up to 5 s for a new worker to activate and switches to it. If that does not happen in time, wait() resolves anyway on the old worker, with controller.stale set.

Member What it is
controller.build The build of the controller bundle in your page, such as 4.2.0+69a79e8a7f20
controller.config.build The build of the service worker it talks to
controller.stale null while they agree, else { controller, worker } with both builds
stale event The builds disagree; event.detail is the stale value
rebind event A later handshake agrees again; event.detail is { build }

When the new worker activates later, the controller switches to it by itself and fires rebind. You do not have to reload. Show the state if you want to:

const showState = () => (status.textContent = controller.stale ? 'Updating' : 'Ready');
controller.addEventListener('stale', showState);
controller.addEventListener('rebind', showState);
showState();

If your page is the older side (it came from a cache), no newer worker will match it and rebind does not come. Show a reload button when stale stays set. register() uses updateViaCache: 'none', so the browser checks the worker script on every update check instead of reading it from its HTTP cache. Deploy STomp covers caching headers for the other files.

Worked example

A small tabbed browser: a tab strip with icons, Back, Forward, Reload, an address bar with search, popups as tabs, a request log per tab, a cookie list and an error page. Four files:

tiny-browser/
  server.mjs          serves everything on one port
  public/index.html   the page
  public/browser.js   the module script
  public/error.html   the error page

Install and run it (Node 22 or newer):

mkdir tiny-browser && cd tiny-browser
npm init -y && npm pkg set type=module
npm install --save-exact @sysce/stomp@nightly holywisp@0.5.3 express@5
npm install "@mercuryworkshop/epoxy-transport@github:Fracital/EpoxyTransport#4d5a277e0e7691e572633d829c17619c2ef647b3"
node server.mjs

Then open http://localhost:8080/. Service workers need a secure context, and localhost counts as one; anywhere else, serve it over HTTPS.

server.mjs

The server serves dist/ at /stomp/, the epoxy build at /epoxy/, your files at /, and runs holyWisp at /wisp/. Install into an existing app has other servers, and Transports and Wisp shows how to use the public relay instead of your own.

// server.mjs: serves the example browser, STomp's dist/, the epoxy
// transport and a wisp endpoint, all on one port.
import { createServer } from 'node:http';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { stompPath } from '@sysce/stomp/path';
import express from 'express';
import { holyWisp } from 'holywisp';

const epoxyPath = dirname(
	fileURLToPath(import.meta.resolve('@mercuryworkshop/epoxy-transport')),
);

const app = express();
app.use('/stomp/', express.static(stompPath));
app.use('/epoxy/', express.static(epoxyPath));
app.use(express.static(fileURLToPath(new URL('public/', import.meta.url))));

const wisp = new holyWisp({
	// test only: let the relay reach a test site on 127.0.0.1
	...(process.env.WISP_ALLOW_LOOPBACK && {
		allowDirectIP: true,
		allowLoopbackIPs: true,
	}),
});
await wisp.start(1);

const server = createServer(app);
server.on('upgrade', (req, socket, head) => {
	if (req.url.startsWith('/wisp/')) wisp.route(req, socket, head);
	else socket.destroy();
});
server.listen(Number(process.env.PORT || 8080), () =>
	console.log(`http://localhost:${server.address().port}/`),
);

WISP_ALLOW_LOOPBACK is only for testing against a site on your own machine. Leave it unset otherwise: a relay that reaches loopback addresses lets any page you proxy reach services on your server.

public/index.html

<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<title>Tiny browser</title>
		<style>
			* { box-sizing: border-box; }
			body {
				margin: 0;
				height: 100vh;
				display: grid;
				grid-template-rows: auto auto 1fr auto;
				font: 14px system-ui, sans-serif;
			}
			#tabs { display: flex; gap: 2px; padding: 4px 4px 0; background: #ddd; }
			.tab { display: flex; align-items: center; gap: 6px; max-width: 14em; border: 0; background: #eee; }
			.tab.active { background: #fff; }
			.tab span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
			.tab canvas { width: 16px; height: 16px; flex: none; }
			#toolbar { display: flex; gap: 4px; padding: 4px; }
			#address { flex: 1; }
			#views { position: relative; }
			#views iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; }
			#views iframe[hidden] { display: none; }
			#log { height: 8em; margin: 0; overflow: auto; font-size: 11px; border-top: 1px solid #ccc; }
			#status { font-size: 12px; color: #555; align-self: center; }
		</style>
	</head>
	<body>
		<div id="tabs"><button id="new-tab" type="button" title="New tab">+</button></div>
		<form id="toolbar">
			<button id="back" type="button" disabled>&larr;</button>
			<button id="forward" type="button" disabled>&rarr;</button>
			<button id="reload" type="button">Reload</button>
			<input id="address" placeholder="Search or type a URL" autocomplete="off" />
			<button id="cookies" type="button">Cookies</button>
			<span id="status">Starting</span>
		</form>
		<main id="views"></main>
		<pre id="log"></pre>
		<script type="module" src="/browser.js"></script>
	</body>
</html>

public/browser.js

// browser.js: a tabbed browser around STomp frames.
import { SearchBuilder, StompController } from '/stomp/controller.mjs';

const settings = {
	// where dist/ is served, and the service worker's scope
	directory: '/stomp/',
	// a proxy-transports module on this origin, and the wisp relay it dials
	transport: {
		module: '/epoxy/index.mjs',
		options: [{ wisp: `${location.origin.replace(/^http/, 'ws')}/wisp/` }],
	},
	search: 'https://duckduckgo.com/?q=%s',
	home: 'https://duckduckgo.com/',
};

const $ = (id) => document.getElementById(id);
const status = (text) => ($('status').textContent = text);
const search = new SearchBuilder(settings.search);

/** turn what the user typed into a URL: a search, or the address itself */
function typed(text) {
	const url = search.query(text.trim());
	// SearchBuilder gives a bare host http://; ask for https:// as Chrome does
	return /^[a-z]+:\/\//i.test(text.trim())
		? url
		: url.replace(/^http:/, 'https:');
}

// A pre hook: runs in every proxied realm before STomp's own hooks. In a
// top document it hands the host a port; the host sends it an icon URL and
// gets the picture back. The <img> is loaded by the proxied page, so the
// request goes through the proxy; the host page itself is outside the
// service worker's scope and would load the icon directly.
function iconHook(stomp) {
	const win = stomp.window;
	if (stomp.kind !== 'document' || !stomp.isTop || win.top === win) return;
	const apply = win.Reflect.apply;
	const bitmap = win.createImageBitmap;
	const Image = win.Image;
	const channel = new win.MessageChannel();
	channel.port1.onmessage = async ({ data: url }) => {
		let picture = null;
		try {
			const image = new Image();
			image.src = url;
			await image.decode();
			picture = await apply(bitmap, win, [
				image,
				{ resizeWidth: 32, resizeHeight: 32, resizeQuality: 'high' },
			]);
		} catch {}
		channel.port1.postMessage({ url, picture }, picture ? [picture] : []);
	};
	win.top.postMessage({ tinyBrowserIcon: true }, '*', [channel.port2]);
}

/** every open tab, in strip order */
const tabs = [];
/** the tab each Frame belongs to */
const tabOf = new Map();
let active = null;

status('Registering service worker');
const registration = await StompController.register(settings.directory);

const controller = new StompController({
	serviceworker: registration,
	transport: settings.transport,
	directory: settings.directory,
	codec: 'xor',
	errorPage: '/error.html',
	hooks: { init: { pre: { source: `(${iconHook})(stomp);` } } },
	onHookError(info) {
		console.warn(`hook ${info.phase} failed in ${info.url}: ${info.message}`);
	},
	// a page asked for a new tab: window.open, target=_blank, a middle click
	onOpen(url) {
		openTab(url);
	},
	// one report per proxied request, with the Frame that made it
	onRequest(info) {
		const tab = info.frame && tabOf.get(info.frame);
		if (!tab) return; // not tied to a tab yet (or an error page)
		const result =
			info.status || `failed (${info.kind ?? 'error'}): ${info.error}`;
		tab.log.push(
			`${info.method} ${result} ${info.destination} ${info.url}${info.cached ? ' (cache)' : ''} ${info.ms} ms`,
		);
		if (tab.log.length > 200) tab.log.shift();
		if (tab === active) showLog();
	},
});

status('Waiting for the service worker');
await controller.wait();
const showState = () =>
	status(controller.stale ? 'Ready (update pending)' : 'Ready');
controller.addEventListener('stale', showState);
controller.addEventListener('rebind', showState);
showState();

function openTab(url) {
	const frame = controller.createFrame();
	frame.element.title = 'Proxied page';
	$('views').append(frame.element);

	const button = document.createElement('button');
	button.type = 'button';
	button.className = 'tab';
	button.innerHTML =
		'<canvas width="32" height="32"></canvas><span>New tab</span><b title="Close">&times;</b>';
	button.onclick = (event) =>
		event.target.tagName === 'B' ? closeTab(tab) : select(tab);
	$('new-tab').before(button);

	const tab = { frame, button, info: null, icon: null, port: null, log: [] };
	tabs.push(tab);
	tabOf.set(frame, tab);

	// the page reported: load, pushState, hashchange, a new title or icon
	frame.addEventListener('navigate', (event) => {
		tab.info = event.detail;
		button.querySelector('span').textContent = tab.info.title || tab.info.url;
		askIcon(tab);
		if (tab === active) showTab();
	});

	select(tab);
	if (url) frame.go(url);
	return tab;
}

function closeTab(tab) {
	const index = tabs.indexOf(tab);
	tabs.splice(index, 1);
	tabOf.delete(tab.frame);
	tab.frame.element.remove();
	tab.button.remove();
	tab.port?.close();
	// there is no frame.close(): drop it from the controller's list by hand
	controller.frames.splice(controller.frames.indexOf(tab.frame), 1);
	if (tab === active) {
		active = null;
		if (tabs.length) select(tabs[Math.min(index, tabs.length - 1)]);
		else openTab(settings.home);
	}
}

function select(tab) {
	active = tab;
	for (const other of tabs) {
		other.frame.element.hidden = other !== tab;
		other.button.classList.toggle('active', other === tab);
	}
	showTab();
	showLog();
}

/** the toolbar follows the active tab */
function showTab() {
	const info = active?.info;
	// leave the address alone while the user is typing in it
	if (document.activeElement !== $('address'))
		$('address').value = info?.url ?? '';
	document.title = info?.title || 'Tiny browser';
	// null means the browser cannot tell (no Navigation API): keep them enabled
	$('back').disabled = info?.canGoBack === false;
	$('forward').disabled = info?.canGoForward === false;
}

function showLog() {
	$('log').textContent = active ? active.log.join('\n') : '';
	$('log').scrollTop = $('log').scrollHeight;
}

/** ask the tab's page for its icon: the one it declared, else /favicon.ico */
function askIcon(tab) {
	if (!tab.port || !tab.info) return;
	const url = tab.info.icon ?? new URL('/favicon.ico', tab.info.url).href;
	if (url === tab.icon) return;
	tab.icon = url;
	tab.port.postMessage(url);
}

// messages from the tabs: the icon hook's port, and the error page
addEventListener('message', (event) => {
	const tab = tabs.find((t) => t.frame.element.contentWindow === event.source);
	if (!tab) return;
	// error.html does not send a navigate report: it says so itself
	if (event.data?.stompError) {
		const { url, kind } = event.data.stompError;
		tab.info = {
			url,
			title: `Error: ${kind}`,
			canGoBack: tab.frame.canGoBack,
			canGoForward: false,
			icon: null,
		};
		tab.button.querySelector('span').textContent = tab.info.title;
		if (tab === active) showTab();
		return;
	}
	if (!event.data?.tinyBrowserIcon || !event.ports[0]) return;
	tab.port?.close();
	tab.port = event.ports[0];
	tab.icon = null;
	tab.port.onmessage = ({ data }) => {
		const canvas = tab.button.querySelector('canvas');
		const context = canvas.getContext('2d');
		context.clearRect(0, 0, 32, 32);
		if (data.url === tab.icon && data.picture)
			context.drawImage(data.picture, 0, 0);
		data.picture?.close();
	};
	askIcon(tab);
});

$('new-tab').onclick = () => {
	openTab();
	$('address').focus();
};
$('back').onclick = () => active?.frame.back();
$('forward').onclick = () => active?.frame.forward();
$('reload').onclick = () => active?.frame.reload();
$('toolbar').onsubmit = (event) => {
	event.preventDefault();
	const text = $('address').value;
	if (!active || !text.trim()) return;
	active.frame.go(typed(text));
	active.frame.element.focus();
};
$('cookies').onclick = async () => {
	if (!active?.info) return;
	const origin = new URL(active.info.url).origin;
	const cookies = await controller.cookies.list(origin);
	const lines = cookies.map(
		(c) => `${c.name}=${c.value} (${c.domain}${c.path})`,
	);
	$('log').textContent =
		`Cookies for ${origin}:\n${lines.join('\n') || '(none)'}`;
};

openTab(settings.home);

// for the console
window.browser = { controller, tabs, openTab };

public/error.html

<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Page unavailable</title>
		<style>
			body {
				font:
					16px/1.5 system-ui,
					sans-serif;
				max-width: 32rem;
				margin: 15vh auto;
				padding: 0 1rem;
			}
			code {
				word-break: break-all;
			}
		</style>
	</head>
	<body>
		<h1 id="title">Page unavailable</h1>
		<p>Could not load <code id="url"></code>.</p>
		<p id="detail"></p>
		<button id="retry" type="button">Try again</button>
		<script>
			// STomp puts the failure here before this page's first script runs
			const info = globalThis.stompError || {};
			const titles = {
				transport: 'Could not reach the site',
				timeout: 'The site took too long',
				routing: 'Something went wrong',
				blocked: 'Blocked by this host',
				controller: 'This tab lost its browser',
			};
			document.getElementById('title').textContent =
				titles[info.kind] || 'Page unavailable';
			document.title = document.getElementById('title').textContent;
			document.getElementById('url').textContent = info.url || location.href;
			document.getElementById('detail').textContent = info.error
				? `${info.kind} (${info.status}): ${info.error}`
				: '';
			// tell the browser UI: this page carries no STomp report of its own
			parent.postMessage({ stompError: info }, '*');
			// the page's URL is the one that failed: reloading retries it
			document.getElementById('retry').onclick = () => location.reload();
		</script>
	</body>
</html>

What to try

  • Type wikipedia.org and press Enter. The browser asks for https://wikipedia.org, and the address bar then shows https://www.wikipedia.org/, where Wikipedia redirects. The tab gets the page's title and icon, and the log lists the page's requests.
  • Click a link, then use the arrows. They are disabled when there is nothing in that direction.
  • Type stomp proxy. It goes to the search template.
  • On a page with a target="_blank" link, click it. It opens as a new tab, not a window.
  • Type https://does-not-exist.invalid/. The error page shows, and the tab title reads Error: transport.
  • Press Cookies on a site that sets cookies.
  • In the console, browser.controller is the controller and browser.tabs the tabs.

To run it with origin isolation, change the controller as Origin isolation shows.

Troubleshooting

The address bar and title stay on the old page when a site fails

Error pages do not send navigate reports. Post a message from your error page, as in Show your own error page. With StompController, frame.url is null while an error page shows.

Popups open as bare windows

You did not pass onOpen. With it, popups reach your code and the page's window.open() returns null.

The tab's icon loads from the real site, or not at all

Your page loaded info.icon itself. Load it through a hook in the proxied page, as in Titles and icons.

info.frame is null in onRequest

The request came from a client that no tab holds (a page's own service worker), its page never said which frame it is in, or it is a failed document whose error page carries no report. Match failed documents by URL, or listen for your error page's message.

Back and Forward stay enabled on a page with no history

canGoBack and canGoForward are null in a browser without the Navigation API. Use the false that back() and forward() resolve to.

Closed tabs still show up in controller.frames

There is no method that removes a frame. Splice it out of controller.frames when you close the tab.

A link with target="_top" replaced my whole page

That happens in same-origin mode with sandbox: null. Keep the default sandbox (it leaves out allow-top-navigation), and use origin isolation for anything public.

More symptoms are in Troubleshooting.

Clone this wiki locally