Repository navigation
Configure STomp
This page is the reference for everything you can pass to STomp and everything you can call on it: the options of StompController and RemoteController, their members, methods and events, Frame, RemoteFrame, SearchBuilder, search suggestions, the omnibox module, and the package exports. Every default here was read from the source on master. If you are setting STomp up for the first time, start with the Bootstrapper quickstart and come back here when you need a specific option.
Contents:
- How configuration works
- Package exports
- Options: core, host callbacks, frames and documents, rewriting, network and cache, request rules, content blocker and shields, assets and names, hooks, passkeys, permissions and the site pool, RemoteController only
- Codecs
- Transport descriptor
- StompController members, methods and events
- RemoteController members, methods and events
- Frame and RemoteFrame
- SearchBuilder
- Search suggestions
- Omnibox
- Data shapes
- Minimal, typical and hardened
- Troubleshooting
You configure STomp with one object, passed to the controller's constructor. There is no global config and no config file: the controller sends what it needs to the service worker in its handshake, and the service worker hands each proxied document the part it needs.
import { StompController } from '@sysce/stomp';
const registration = await StompController.register('/stomp/');
const controller = new StompController({
serviceworker: registration,
transport: { module: '/epoxy/index.mjs', options: [{ wisp: 'wss://holywisp.fracit.al/' }] },
directory: '/stomp/',
// every other option is optional
});
await controller.wait();Most options are fixed for the life of the controller. Four things can change at run time without a new controller:
| What | How |
|---|---|
| Request rules | controller.setRules(rules) |
| Transport | controller.setTransport(transport) |
| Content blocker lists |
controller.setAdblockLists(lists), controller.refreshAdblockLists()
|
| Per-site shields |
controller.shields.set(host, patch), controller.shields.replace(list)
|
For anything else, construct a new controller (in practice, reload the host page). This includes hook files given as { url }: the controller fetches them once, when it is constructed.
Pick the controller by where the proxy runs:
-
StompControllerruns the proxy on the host page's own origin. Proxied pages are same-origin with your page, so this mode is for development and in-house use. It is not a security boundary. -
RemoteControllerruns the realStompControllerin a hidden frame on a second origin and shows proxied pages in cross-origin, sandboxed frames. Use it in production. See Origin isolation.
Both take nearly the same options. The tables below mark what differs.
The ES module dist/controller.mjs, with types in dist/types/controller/index.d.ts.
| Export | Kind | What it is |
|---|---|---|
StompController |
class (also the default export) | The same-origin controller |
RemoteController |
class | The host-side controller for origin isolation |
Frame, RemoteFrame
|
classes | What createFrame() returns; you do not construct them yourself |
SearchBuilder |
class | Turns address bar text into a URL (SearchBuilder) |
SEARCH_ENGINES |
array | The search engines suggest() knows (search suggestions) |
searchEngine(name) |
function | The SEARCH_ENGINES entry for an id or a results template, or null
|
Http3Transport |
class | The HTTP/3 wrapper for a transport instance you construct yourself (Transports and Wisp) |
DEFAULT_ASSETS |
object | The default file names of dist/ (assets), the same object as StompController.DEFAULT_ASSETS
|
DEFAULT_NAMES |
object | The fallback helper names (names) |
DEFAULT_SANDBOX |
string | The default sandbox attribute of proxied frames |
BUILD |
string | This bundle's build, such as 4.2.0+69a79e8a7f20 (also controller.build) |
NAVIGATION_WAIT_MS, REPORT_GRACE_MS, REGISTER_WAIT_MS
|
numbers |
30000, 1000, 30000: the waits of go() and register() described below |
activated(worker) |
function | Resolves when a ServiceWorker reaches activated, rejects if it becomes redundant
|
The module also exports helpers such as navigateReport, openRequest, cookieJar, passkeyManager, frameOfSource, entriesAcross and runsExpectation. STomp's own controller frame and tests use them. They are not part of the host API and can change without notice.
Type-only exports include ControllerInit, RemoteControllerInit, TransportDescriptor, Http3DescriptorOptions, Http3Options, WispWebTransportOptions, CarrierInfo, Config, ConfigCodec, Assets, HelperNames, InitHooks, HookScript, HookContext, HookErrorInfo, RequestRule, RequestRuleMatch, RequestRuleAction, NavigateInfo, RequestInfo, RequestEvent, CookieRecord, CookieJar, StaleInfo, FrameInfo, AdblockOptions, AdblockList, AdblockApplied, PermissionRequest, PasskeysInit, PasskeyRequest, PasskeyAnswer, PasskeyInfo, PasskeyManager, RemotePasskeysInit, RemotePasskeyRequest, SearchEngine, SuggestOptions and ProxyTransport.
A few types that options use are not exported by name: the shields entry, the site pool option, RemoteController's request and permission events, and the shards option. Derive them from the init types:
import type { ControllerInit, RemoteControllerInit } from '@sysce/stomp';
type SiteShields = NonNullable<ControllerInit['shields']>[number];
type SitePoolInit = Exclude<ControllerInit['sitePool'], false | undefined>;
type RemoteRequestEvent = Parameters<NonNullable<RemoteControllerInit['onRequest']>>[0];TypeScript: compile with "moduleResolution": "bundler" (what Vite and esbuild projects use). The declarations import their siblings without file extensions, which "nodenext" and "node16" refuse; with skipLibCheck the errors go away, but many types silently become any.
A CommonJS module for your server. It exports one value, stompPath: the absolute path of the package's dist/ directory, which you serve as your STomp directory. It works from ES modules too:
import { stompPath } from '@sysce/stomp/path';
app.use('/stomp/', express.static(stompPath));The ES module dist/omnibox.mjs, with types in dist/types/omnibox/index.d.ts. It is the address bar dropdown described under Omnibox, and it exports SEARCH_ENGINES and searchEngine too. No proxied page and no controller bundle loads it, so a host that does not import it pays nothing for it.
import { attachOmnibox, visitHistory, tabRows } from '@sysce/stomp/omnibox';Without a bundler, import /stomp/omnibox.mjs from wherever you serve dist/.
dist/Controller.js defines the globals StompController and StompRemoteController. dist/SearchBuilder.js defines SearchBuilder. dist/omnibox.js defines Omnibox, an object with every export of @sysce/stomp/omnibox. Use them when your page has no module loader:
<script src="/stomp/Controller.js"></script>
<script src="/stomp/SearchBuilder.js"></script>
<script src="/stomp/omnibox.js"></script>Controller.js has no SEARCH_ENGINES global. A classic-script page reads Omnibox.SEARCH_ENGINES.
The tables list every public option of ControllerInit (StompController) and RemoteControllerInit. The "Remote" column says whether RemoteController takes the option too.
| Option | Type | Default | What it does | Remote |
|---|---|---|---|---|
serviceworker |
ServiceWorker or ServiceWorkerRegistration
|
required | STomp's service worker. Given a registration, the controller takes its active, waiting or installing worker and shakes hands once it is activated (30 s at most). | No: the controller frame registers its own |
transport |
ProxyTransport instance or descriptor
|
required | Where proxied traffic goes. A descriptor runs in a dedicated transport worker. An instance runs in your page. | Descriptor only |
directory |
string or URL
|
your page's directory; '/stomp/' for RemoteController
|
The directory you serve dist/ from and the service worker's scope. StompController resolves it against the page and throws an Error if it is on another origin. Its default is the directory of the external script file that calls the constructor, which for inline and module scripts is your page's directory, so always pass it. For RemoteController it is a pathname on the proxy origin. |
Yes |
id |
string |
kept per origin | The controller's id: 1 to 32 characters of [A-Za-z0-9_-] (a TypeError otherwise). It is part of every routed URL (/stomp/<id>/...). Without one, the controller keeps an 8-character id in the host origin's storage from visit to visit, so reloads, history entries and copied links keep working. Passing an id that another open controller uses replaces that controller. |
Yes |
codec |
'xor', 'generic', 'base64', 'aes'
|
'xor' |
How a real URL is encoded into the routed URL. See Codecs. | Yes |
id is empty until wait() resolves when you do not pass one. Read controller.id after that.
const controller = new StompController({
serviceworker: await StompController.register('/stomp/'),
transport: { module: '/epoxy/index.mjs', options: [{ wisp: 'wss://holywisp.fracit.al/' }] },
directory: '/stomp/',
codec: 'xor',
});Each callback has an event twin on the controller, so you can use either. All of them are optional; leaving onRequest out means the service worker builds no reports at all.
| Option | Signature | What it reports | Remote |
|---|---|---|---|
onNavigate |
(info: NavigateInfo, frame: Frame) => void |
The page reported where it is: on load, pushState, hashchange, title or icon changes. Also a navigate event on the controller (detail: { info, frame }) and on the frame (detail: info). |
Yes, with a RemoteFrame
|
onOpen |
(url: string, frame: Frame) => void |
The page wants a new tab: window.open, target="_blank" or a named target, a middle or modifier click. The page's window.open returns null, as with a popup blocker. Also an open event (detail: { url, frame }). Without onOpen, popups open natively as bare proxied tabs. |
Yes |
onRequest |
(info: RequestEvent) => void |
One report per proxied request, after it finished: real URL, status, timing, cache use, the frame it belongs to. See RequestInfo. Also a request event (detail is the report). |
Yes, frame is a RemoteFrame
|
onHookError |
(info: HookErrorInfo, frame: Frame | null) => void |
A hook threw in a proxied realm, or a hook URL could not be fetched (phase: 'url', frame null). Also a hookerror event and an entry in controller.hookErrors. |
Yes, but called with info only |
onPermissionRequest |
(request: PermissionRequest) => boolean | null | Promise<...> |
A site asks for a permission (geolocation, camera, notifications) that the browser already granted the proxy origin for another site. Resolve true to grant, false to deny, null when the user closed your prompt. Without it, such requests are dismissed. A site's first request still gets the browser's own prompt. |
Yes. Frames that should reach the browser's prompts need an allow attribute |
onShieldsChange |
(host: string, state: SiteShields) => void |
Called after controller.shields.set(), so you can persist the change. |
Yes |
Why the frame is passed: one controller serves every tab. info.frame is how a request log, a title or a favicon finds its tab. A request from a nested frame, an about:blank child or a worker is attributed to the top frame that holds it. Reports from the document itself wait up to 3 s for the page to say which frame it is in (1.5 s for the subresources its head loads), so frame is null only for requests no frame holds, such as a page's emulated service worker.
const tabs = new Map(); // Frame -> your tab object
const controller = new StompController({
// ...core options
onNavigate(info, frame) {
const tab = tabs.get(frame);
tab.title = info.title;
tab.url = info.url;
tab.icon = info.icon; // null when the page declared none
tab.canGoBack = info.canGoBack !== false;
},
onOpen(url, frame) {
openTab(url); // create a new frame and call frame.go(url)
},
onRequest(info) {
if (info.status === 0) console.warn('failed', info.url, info.kind, info.error);
},
});| Option | Type | Default | What it does | Remote |
|---|---|---|---|---|
sandbox |
string or null
|
DEFAULT_SANDBOX |
The sandbox attribute createFrame() puts on proxied frames. The default leaves out allow-top-navigation, so <a target="_top"> and window.open(url, '_top') cannot navigate your page. null sets no attribute (StompController only). |
Yes, string only |
frameAncestors |
string[] |
none | Origins allowed to frame proxied documents, sent as Content-Security-Policy: frame-ancestors. RemoteController sets it to your host origin for you. |
Set for you |
errorPage |
string |
built-in pages | Your page for a document the proxy failed to produce: unreachable origin, timeout, routing error, a blocking rule. Must be same-origin with the service worker (an Error otherwise). It is served under the frame's routed URL with the failure's status, never cached, with globalThis.stompError = { url, status, error, kind } in its head. location.reload() in it retries. See examples/error.html. |
Yes, a path on the proxy origin |
allowInvalidJs |
boolean |
true |
A script the rewriter cannot parse runs unmodified, as in a browser that does not know the syntax. false makes it throw a SyntaxError naming the rewriter's error, so a broken rewrite is loud while you develop. |
Yes |
membrane |
boolean |
true |
The window membrane: windows of other proxied sites reach a page through a proxy that acts as the browser's cross-origin window. false turns it off for a site it breaks. The option already reaches every document, but the membrane itself is still being built, so both values behave the same on master today. |
Yes |
serviceWorkers |
boolean |
true |
Emulated service workers: a page's navigator.serviceWorker registers workers that run in a dedicated Worker the controller starts, never a real registration on the proxy origin (docs/service-workers.md). Leave it on: with false pages have no navigator.serviceWorker, which a site can read as a proxy tell. A page that never uses it costs nothing. |
Yes, hosted by the controller frame |
The error page's kind is one of transport (status 502), timeout, routing, blocked (403, from a rule) or controller (the routed URL names a controller that is gone and no live controller with the same codec can take over).
const controller = new StompController({
// ...core options
errorPage: '/error.html',
// loud rewriter failures while you develop
allowInvalidJs: location.hostname !== 'localhost',
});<!-- /error.html -->
<script>
const { url, status, error, kind } = globalThis.stompError || {};
document.title = kind === 'blocked' ? 'Blocked' : 'Page unavailable';
</script>The global's name is stompError unless you set names.error (names).
STomp rewrites HTML, CSS and JavaScript with its Rust core module, core.wasm. There is no JavaScript fallback rewriter to choose any more: the controller loads core.wasm before its first handshake, and a host that does not serve it gets a rejected wait() naming the asset. The options you have are about where scripts are rewritten.
| Option | Type | Default | What it does | Remote |
|---|---|---|---|---|
rewriteWorkers |
number |
half the cores, 1 to 4 | How many dedicated Workers (rewriteWorker.js) rewrite scripts for the service worker, whose own thread rewrites one script at a time. A large bundle is split among them. 0 starts none. Values are floored and clamped to 0 to 16. |
Yes, started by the controller frame |
rewriteTimeout |
number (ms) |
10000 |
How long the service worker waits for a rewrite worker before it rewrites the script itself and stops using that worker. Clamped to 50 to 120000. | Yes |
Whenever no rewrite worker answers (none started, one crashed, your page closed), the service worker rewrites the script itself. The output is the same either way. onRequest tells you where each script was rewritten (rewriteIn).
// a kiosk with many cores and heavy sites
new StompController({ /* ...core options */ rewriteWorkers: 4, rewriteTimeout: 20000 });| Option | Type | Default | What it does | Remote |
|---|---|---|---|---|
cache |
boolean |
true |
The HTTP cache in the service worker, which keeps and revalidates responses as Chrome's HTTP cache does (docs/http-cache.md), and the rewrite cache next to it. false turns both off. |
Yes |
rules |
RequestRule[] |
[] |
Declarative request rules. See Request rules. | Yes |
debugTransport |
boolean |
localStorage['stomp:debug-transport'] === '1' |
Prints a [net] line on your console for each connection the transport opens and what it rides (HTTP/1.1, HTTP/2, HTTP/3, WebTransport or WebSocket), and each HTTP/3 fallback with its reason. |
Yes, printed in your page |
carrierHost |
boolean |
true |
A transport given a wisp URL shares one wisp connection per origin through a SharedWorker, so a reload or a second tab does not open a new one. false gives each transport its own. |
No |
The rewrite cache keeps a script's rewritten output, keyed by its body, URL, script type, config and build. It keeps at most 3000 entries, 48 MiB each and 512 MiB in all, oldest first out, and never keeps an answer to a request with Authorization, one marked no-store or private, or one fetched with cookies unless it says public. clearCache() drops both caches. onRequest reports cached, revalidated and rewriteCache (hit, miss or skip).
new StompController({ /* ...core options */ cache: false, debugTransport: true });Rules run in the service worker on the real URL, after STomp has rebuilt Origin, Referer and cookies, so a rule's header wins. The first rule that matches applies, and onRequest reports its index as info.rule.
match field |
Type | Matches |
|---|---|---|
url |
string |
A URLPattern string tested against the real URL |
method |
string[] |
Request methods, case-insensitive |
destination |
string[] |
Fetch destinations (document, iframe, script, style, image, ...). A fetch() or XHR is 'empty' here, although onRequest reports it as 'fetch'
|
site |
string[] |
'same-origin', 'same-site', 'cross-site' or 'none', as Sec-Fetch-Site would say |
A field you leave out matches everything.
action |
Result |
|---|---|
'block' |
403 with an empty body. A blocked document shows your errorPage with kind: 'blocked'. |
{ status } |
Answers with that status and an empty body. Nothing goes upstream. |
{ redirect } |
Answers 307 to that real URL, routed through the proxy. |
{ requestHeaders, responseHeaders } |
Sets headers; null deletes one. |
An action object is read in that order: status first, then redirect, then the headers.
const rules = [
// any host, any port: a pattern without a port matches default ports only
{ match: { url: '*://*:*/ads/*' }, action: 'block' },
// "*.example.com" does not match example.com itself; list both if you need it
{ match: { url: 'https://*.example.com/track*' }, action: { status: 204 } },
{
match: { url: 'https://api.example.com/*', method: ['POST'] },
action: { requestHeaders: { 'x-client': 'my-app', cookie: null } },
},
];
const controller = new StompController({ /* ...core options */ rules });
await controller.setRules([...rules, { match: { destination: ['font'] }, action: 'block' }]);URLPattern exists in Chrome and Edge. Where it is missing, or a pattern does not compile, STomp skips that rule with one console warning and applies the rest. A rule with no url works in every browser.
The built-in content blocker is Brave's adblock-rust compiled to blocker.wasm (docs/adblock.md). The service worker fetches the filter lists through your transport, compiles them and keeps the engine in CacheStorage. A blocked request never reaches the transport and is a network error to the page. Cosmetic filters, procedural filters and scriptlets apply in every document.
| Option | Type | Default | What it does | Remote |
|---|---|---|---|---|
adblock |
boolean or AdblockOptions
|
on, best effort | Left out: on if it can be. Without blocker.wasm or the lists, the proxy runs unfiltered, says so once on the console, and no page waits. true or an object: you ask for it, so the first navigation waits for the engine, 5 s at most. false: nothing of it is fetched or run. |
Yes |
adblockLists |
(string | AdblockList)[] |
the defaults | The lists to start with in place of the defaults, for example what your filter list editor saved. Ignored when adblock is false. |
Yes |
shields |
SiteShields[] |
none | Per-site settings you persisted, applied from the first handshake. | Yes |
AdblockOptions:
| Field | Type | Default |
|---|---|---|
lists |
(string | AdblockList)[] |
EasyList, EasyPrivacy and six uBlock Origin lists (filters, unbreak, badware risks, privacy, resource abuse, quick fixes) |
resources |
string (URL) |
adblock-resources.json in your directory (uBlock Origin's scriptlets and redirect resources) |
engine |
string (URL) |
none: a serialized engine to load in place of fetching and compiling the lists |
refresh |
number (hours) |
24 |
AdblockList is { url, trusted?, format?, filters?, name? }. trusted: true lets a list use the trusted-* scriptlets, which edit cookies, storage and responses; only uBlock Origin's own default lists are trusted. format: 'hosts' reads a hosts file. filters is inline filter text compiled in place of fetching url. name is for your UI only.
A SiteShields entry is { host, enabled, mode, httpsUpgrade?, blockScripts?, blockFingerprinting?, fingerprint?, cookies?, forget? }. A host with no entry of its own takes the entry for host '*' if you have one, and is neutral otherwise: the blocker as configured, no forced HTTPS upgrade, cookies as SameSite allows. An entry you create with controller.shields.set(host, patch) starts from these values, which is also what shields.get(host) returns for a host without one: enabled: true, mode: 'standard', httpsUpgrade: 'upgrade', blockScripts: false, blockFingerprinting: true, cookies: 'third-party', forget: false. Until an entry exists, the service worker treats the host as neutral, not with these values. Shields never turn off STomp's rewriting. forget: true is yours to act on: call controller.forgetStorage(origin) and controller.cookies.clear(origin) when the site's last tab closes.
const saved = JSON.parse(localStorage.getItem('shields') || '[]');
const controller = new StompController({
// ...core options
adblock: { refresh: 12 },
shields: saved,
onShieldsChange() {
localStorage.setItem('shields', JSON.stringify(controller.shields.all()));
},
});
// the user turns the blocker off for one site
controller.shields.set('www.example.com', { mode: 'allow' });assets tells STomp what you called its files when you serve dist/ under other names, so that no URL the browser requests carries the package name. Pass the same object to StompController.register(), which needs serviceWorker.
| Key | Default file | What it is |
|---|---|---|
serviceWorker |
serviceWorker.js |
The service worker |
injectDocument, injectWorker
|
injectDocument.js, injectWorker.js
|
The inject bundles for documents and workers (codecs xor, generic) |
injectDocumentFull, injectWorkerFull
|
injectDocumentFull.js, injectWorkerFull.js
|
The same with crypto-js (codecs aes, base64) |
rewriterLib |
rewriterLib.js |
The rewriter library every proxied top loads. Missing: wait() rejects |
core |
core.wasm |
The rewriter, CSS scanner and public suffix lookup. Missing: wait() rejects |
transportWorker |
transportWorker.js |
The Worker that hosts a transport descriptor |
rewriteWorker |
rewriteWorker.js |
The rewrite Workers |
blocker |
blocker.wasm |
The content blocker engine |
adblockResources |
adblock-resources.json |
The blocker's default scriptlets and redirect resources |
rtcWorker, rtc, rtcStack
|
rtcWorker.js, rtc.wasm, rtcStack.js
|
WebRTC over wisp, loaded the first time a page uses RTCPeerConnection
|
controllerFrame, controllerFrameScript
|
controllerFrame.html, controllerFrame.js
|
RemoteController's hidden frame and its script |
siteFrameScript |
siteFrame.js |
The site pool's agent frame script |
omnibox |
omnibox.js |
The address bar dropdown (Omnibox). STomp never requests it. Your page loads it by this name |
dist/ also has controller.mjs, Controller.js, SearchBuilder.js and omnibox.mjs, which your page loads by whatever URL you give it, and codec.wasm and build.json, which nothing requests at run time.
StompController.DEFAULT_ASSETS holds the default names, the table's middle column. It is the same object as the DEFAULT_ASSETS export, and the one way to read the names from the classic Controller.js. Use it for a file your page names itself, so each name comes from one place: assets.omnibox || StompController.DEFAULT_ASSETS.omnibox. The omnibox key is there for that reason. The controller accepts it in assets and does nothing with it.
STomp asks for rewriterLib, core, the document bundles, transportWorker, rewriteWorker, blocker, controllerFrame, controllerFrameScript and siteFrameScript as <name>?<hash of the bytes>, so you can serve those URLs with Cache-Control: immutable. See Deploy STomp.
const assets = {
serviceWorker: 'sw.js',
injectDocument: 'doc.js',
injectWorker: 'wrk.js',
injectDocumentFull: 'docf.js',
injectWorkerFull: 'wrkf.js',
rewriterLib: 'lib.js',
core: 'c.wasm',
transportWorker: 'net.js',
rewriteWorker: 'rw.js',
blocker: 'k.wasm',
adblockResources: 'res.json',
rtcWorker: 'rtcw.js',
rtc: 'rtc0.wasm',
rtcStack: 'rtcs.js',
controllerFrame: 'cf.html',
controllerFrameScript: 'cf.js',
siteFrameScript: 'sf.js',
omnibox: 'ob.js',
};
const dir = '/static/v/';
const { StompController } = await import(`${dir}app.mjs`); // controller.mjs, renamed
const registration = await StompController.register(dir, { assets });
const controller = new StompController({ serviceworker: registration, transport, directory: dir, assets });
// a file your page loads itself, named from the same object
const omnibox = document.createElement('script');
omnibox.src = dir + (assets.omnibox || StompController.DEFAULT_ASSETS.omnibox);
document.head.append(omnibox);Deploy STomp covers vendoring dist/ from the deploy's side.
A key you leave out keeps its default name.
The rewriter and the inject bundles meet on a few global names. names sets your own.
| Key | What it names | Default |
|---|---|---|
access |
The access API every rewritten script calls | Minted once per host origin ($ and 4 characters) and kept in its localStorage
|
globalProxy |
The stand-in marker on location and eval
|
Minted per host origin, $ and 12 characters |
globalName |
The stand-in name marker and the key of STomp's message envelope | Minted per host origin, $ and 12 characters |
client |
The object that holds the real windows | Minted per controller, $ and 16 characters, never told to any page |
error |
The global your error page reads | stompError |
DEFAULT_NAMES ($s$j, $s$L, $s$N, $P$s, stompError) are only the fallbacks for code that runs where no controller named anything. Per-origin names keep a STomp proxied through your STomp from meeting yours.
Each name must be an identifier that no plain window has. A reserved word, a name such as top or window, two equal names or an unknown key throw a TypeError from the constructor. Leave client unset: a fixed client name is one every page could learn, and a page that can name it reaches the real windows. Set error if your build renames identifiers in your error page.
new StompController({ /* ...core options */ names: { error: 'pageFailure' } });Hooks run your code inside every proxied realm: the page, nested frames, about:blank children, popups and srcdoc frames, and workers if you set workers: true.
| Field | Type | Default | What it does |
|---|---|---|---|
hooks.init.pre |
{ source } or { url }
|
none | Runs before the inject installs its hooks: natives are still untouched |
hooks.init.post |
{ source } or { url }
|
none | Runs after the inject's hooks, before the page's first script |
hooks.workers |
boolean |
false |
Also run in dedicated and shared workers |
A hook is source text, not a function. It runs as the body of a function whose one parameter is stomp (a HookContext), with this set to the realm's global. { url } is fetched once, with cache: 'no-store', when the controller is constructed; with RemoteController the controller frame fetches it from the proxy origin. A URL that fails becomes a hookerror with phase: 'url', and the controller runs without that hook. A bad shape is a TypeError from the constructor.
HookContext is { url, origin, isTop, nested, kind, phase, names, frameId, window }: the page's real URL and origin, whether it is the outermost proxied document, whether it is a child of one, 'document', 'worker' or 'sharedWorker', 'pre' or 'post', the helper names, the controller's id, and the realm's real global.
Hook code is trusted host code with the realm's real globals, such as the real top in same-origin mode. Whatever it leaves on the window, the page can reach. Keep references in closures. A throw is logged in the realm and reported to you, never thrown at the page.
new StompController({
// ...core options
hooks: {
init: {
post: {
source: `if (stomp.kind === 'document')
self.addEventListener('DOMContentLoaded', () => {
const style = document.createElement('style');
style.textContent = '.ad { display: none !important }';
document.head.append(style);
});`,
},
},
},
onHookError(info) {
console.warn('hook failed', info.phase, info.url, info.message);
},
});examples/hooks/hide-ads.js is a fuller version as a file, for { url: '/hooks/hide-ads.js' }.
| Option | Type | Default | What it does | Remote |
|---|---|---|---|---|
passkeys |
PasskeysInit |
off | STomp becomes the passkey provider for proxied sites, as a password manager is. WebAuthn cannot work through a proxy, since the browser binds credentials to the proxy's origin. The service worker keeps one non-extractable key pair per passkey, bound to the site's real relying party id. passkeys.onRequest(request) is called for every create and sign-in; resolve { credential?, userVerified? } or null. Set userVerification: true only if you verify the user yourself. docs/passkeys.md
|
Yes |
onPermissionRequest |
function | none | See Host callbacks and docs/permissions.md. | Yes |
sitePool |
{ origins: string[] } or false
|
false |
Shows each proxied site from one of a few origins (other ports of your host), so the browser gives each a process of its own. Every slot must serve your directory with Origin-Agent-Cluster: ?1. Only used in a secure context; a slot that does not answer falls back to your page's origin. docs/site-pool.md
|
Yes |
new StompController({
// ...core options
passkeys: {
async onRequest(request) {
const ok = confirm(`${request.rpId} wants to ${request.type === 'create' ? 'save' : 'use'} a passkey`);
if (!ok) return null;
return request.type === 'get' ? { credential: request.credentials?.[0]?.id } : {};
},
},
});| Option | Type | Default | What it does |
|---|---|---|---|
proxyOrigin |
string |
required | The origin that serves dist/ and the proxied pages, such as https://proxy.example.com. It must differ from your page's origin (an Error otherwise). Keep it on the same site as your page where you can; see Origin isolation. |
pollInterval |
number (ms) |
500 |
How often each RemoteFrame asks the controller frame for its URL, title and history state, as a fallback to the page's own reports. 0 turns the poll off. |
The transport descriptor's module must be on the proxy origin. A relative path such as /epoxy/index.mjs is resolved there.
RemoteController does not take serviceworker, a transport instance, frameAncestors, carrierHost or sandbox: null.
The controller frame trusts whichever page embeds it, taken from its referrer when it loads. To lock it to your host, list your origins in the stomp-allowed-origins meta of the controllerFrame.html you serve:
<meta name="stomp-allowed-origins" content="https://app.example.com" />A page from any other origin then gets "Embedding origin is not allowed." in the hidden frame, and its wait() never settles.
The controller frame reads your origin from its referrer, so your host page must send one. With Referrer-Policy: no-referrer (a header or a <meta name="referrer">) the frame cannot tell who embeds it and wait() never settles. The browser default, strict-origin-when-cross-origin, works, and so do origin and strict-origin.
import { RemoteController } from '@sysce/stomp';
const controller = new RemoteController({
proxyOrigin: 'https://proxy.example.com',
directory: '/stomp/',
transport: { module: '/epoxy/index.mjs', options: [{ wisp: 'wss://holywisp.fracit.al/' }] },
pollInterval: 1000,
});
await controller.wait();The codec decides what the last segment of a routed URL looks like: /stomp/<id>/<kind>/<encoded>. It is a choice among four built-in codecs; you cannot plug in your own functions. The service worker draws the key once per scope and keeps it in its database.
| Codec | What a route looks like | Notes |
|---|---|---|
'xor' (default) |
/stomp/TTUgyC5U/html/0ew3jIHFgAf5R645TPYPzrPG_bUcEw |
Every byte of the URL XORed with a keyed stream, in URL-safe base64. No character of the site shows. Not encryption: the key is in every proxied realm. Also seals fragments (#~<sealed>) and GET form fields. docs/codec.md
|
'generic' |
/stomp/TTUgyC5U/html/https:$2f$2fexample$2ecom$2fa$3fb |
The URL itself, with characters outside -_~:0-9A-Za-z written as $hh. Readable, useful for debugging. |
'base64' |
/stomp/TTUgyC5U/html/aHR0cHM6Ly9leGFtcGxlLmNvbS9hP2I$3d |
Base64 of the URL, escaped as above. No key. Loads the Full inject bundles, which carry crypto-js. |
'aes' |
/stomp/TTUgyC5U/html/U2FsdGVkX1$2f89FNptF$2fEoU3... |
crypto-js AES with a key from Math.random(), so treat it as obfuscation. A random salt makes the same URL encode differently each time. Loads the Full bundles. |
Use xor unless you have a reason not to. It is the codec docs/codec.md specifies and the codec and fragments test suites check. Unlike generic, no part of the site shows in the route, and unlike aes and base64, it does not load crypto-js into every frame.
To turn a routed URL back into the real one, call controller.unroute(url). Do not parse routes yourself.
const routed = await controller.route('https://example.com/a?b#c');
const real = await controller.unroute(routed); // 'https://example.com/a?b#c'A descriptor is how you hand STomp a transport it should construct itself. The full story, including when to pick epoxy or libcurl, is on Transports and Wisp.
| Field | Type | Default | What it does |
|---|---|---|---|
module |
string |
required | URL of an ES module whose default export is a ProxyTransport class, importable in a worker (epoxy and libcurl qualify). Resolved against your page, or against the proxy origin for RemoteController. |
options |
unknown[] |
[] |
Constructor arguments, such as [{ wisp: 'wss://holywisp.fracit.al/' }]
|
host |
'worker' or 'page'
|
'worker' |
Where the transport runs. In the transport worker, a proxied page's synchronous XHR can complete. 'page' imports it in your page. |
http3 |
boolean or Http3DescriptorOptions
|
off | HTTP/3 over the transport's wisp UDP streams for origins that offer it. Needs epoxy and a relay that carries UDP. Fields: force, dns, timeout (10000 ms), wait (300 ms), module, pem. docs/http3.md
|
webTransport |
boolean or WispWebTransportOptions
|
off | Wisp over the relay's WebTransport session instead of its WebSocket, when the relay has one. Fields: url, discovery, timeoutMs, lanes. Epoxy only. docs/webtransport.md
|
shards |
number or { max, start }
|
max 1 plus half the cores (at most 4 extra), start 1 |
How many threads the transport's TLS may run on (host: 'worker', epoxy with a wisp URL). Clamped to 1 to 16. |
If the transport worker cannot start or cannot import the module, the page imports it instead and the controller fires transporthost. If that fails too, every request fails at once until you call setTransport().
const transport = {
module: '/epoxy/index.mjs',
options: [{ wisp: 'wss://holywisp.fracit.al/' }],
http3: true,
webTransport: true,
};| Member | What it does |
|---|---|
StompController.DEFAULT_ASSETS |
The default file names of dist/, keyed like init.assets (serviceWorker: 'serviceWorker.js', omnibox: 'omnibox.js' and the rest). Read-only in the types. See assets. |
StompController.register(directory?, { assets?, updateViaCache? }) |
Registers <directory><assets.serviceWorker> with directory as its scope and updateViaCache: 'none' unless you pass another value. Resolves with the registration once its worker is activated, or after 30 s with whatever it has, so a worker stuck installing never hangs your page. Throws if the browser has no service workers. Pass directory: the default is the directory of the calling script's file, or of your page for inline and module scripts. |
| Member | Type | What it is |
|---|---|---|
config |
Config |
The config sent to the service worker. config.directory is the controller's address (/stomp/<id>/), config.scope the directory (/stomp/). |
directory |
URL |
The directory you gave, resolved |
id |
string |
The id in use; empty until wait() resolves when you gave none |
build |
string |
This bundle's build, the same as BUILD
|
stale |
{ controller, worker } | null |
Set while a service worker of another build is in charge (a deploy the browser has not finished installing) |
isReady |
boolean |
Whether the latest handshake was answered |
serviceworker |
ServiceWorker |
The worker the controller talks to now |
transport |
ProxyTransport |
The transport in use. For a worker-hosted descriptor, a proxy to it, so controller.transport.request() still works from your console. |
transportHost |
'worker' | 'page' |
Where the transport runs |
carrier |
CarrierInfo | null |
What the transport's wisp connection rides (webtransport or websocket), once known |
frames |
Frame[] |
Every frame createFrame() made |
hookErrors |
HookErrorInfo[] |
Every hook error so far, newest last |
cookies |
CookieJar |
The cookie jar, see below |
passkeys |
PasskeyManager |
list(rpId?), delete(id), clear(rpId?) over the stored passkeys |
shields |
Shields |
get(host), has(host), set(host, patch), all(), replace(list)
|
siteMode |
boolean |
Whether the controller shows sites from a site pool |
| Method | Returns | What it does |
|---|---|---|
wait() |
Promise<void> |
Resolves when the service worker has a server for this controller. If the worker is another build, the controller updates it, waits up to 5 s for the new one to activate and rebinds; otherwise it resolves on the old worker with stale set. Rejects if core or rewriterLib cannot be fetched. |
createFrame(iframe?) |
Frame |
Wraps your <iframe>, or makes one, and sets its sandbox. You place frame.element. |
route(url) |
Promise<string> |
The routed URL for a real URL |
unroute(url) |
Promise<string | null> |
The real URL for a routed one; null for anything that is not a route |
setTransport(transport) |
Promise<void> |
Swaps the transport. Pass a descriptor when transportHost is 'worker' and an instance when it is 'page'; the other kind is a TypeError. Requests in flight finish on the old one. |
rebind(worker?) |
Promise<void> |
Talks to another service worker (default: the registration's active one) and shakes hands again. The controller does this on its own when a new worker activates. |
setRules(rules) |
Promise<void> |
Replaces the request rules |
clearCache() |
Promise<void> |
Drops the HTTP cache and the rewrite cache |
suggest(text, options?) |
Promise<string[]> |
A search engine's completions for text, asked through the transport. Waits for the transport only, so it works before wait() resolves. See search suggestions. |
forgetStorage(origin) |
Promise<void> |
Clears a site's localStorage, sessionStorage, IndexedDB, Cache Storage and passkeys on the proxy origin. Cookies are separate: cookies.clear(origin). |
adblockDefaults() |
AdblockList[] |
The default lists, untouched by setAdblockLists; empty with adblock: false
|
getAdblockLists() |
AdblockList[] |
The lists in force now |
setAdblockLists(lists) |
Promise<{ applied: 'live' | 'off' }> |
Rebuilds the engine from new lists. The old lists keep serving until the new engine compiles. |
refreshAdblockLists() |
Promise<{ applied: 'live' | 'off' }> |
Fetches and compiles the current lists again |
The cookie jar is for your page only; proxied pages never reach it:
| Method | What it does |
|---|---|
cookies.get(url) |
The Cookie header the proxy would send to url
|
cookies.set(url, setCookie) |
Applies one or more Set-Cookie values as if url had sent them |
cookies.list(origin?) |
Every stored CookieRecord, or those a page of origin could receive |
cookies.clear(origin?) |
Forgets every cookie, or those of origin. Without an origin it also forgets the kept controller ids, so the next controller gets a new one. |
await controller.cookies.set('https://example.com/', 'session=abc; Path=/; Secure');
console.log(await controller.cookies.get('https://example.com/')); // 'session=abc'StompController is an EventTarget. Every event is a CustomEvent.
| Event | detail |
When |
|---|---|---|
navigate |
{ info: NavigateInfo, frame } |
A page reported where it is (the onNavigate twin) |
open |
{ url, frame } |
A page wants a new tab (the onOpen twin) |
request |
RequestEvent |
A proxied request finished (only with onRequest set) |
hookerror |
{ info: HookErrorInfo, frame } |
A hook threw or a hook URL failed |
stale |
{ controller, worker } |
The handshake met a service worker of another build that could not be replaced in time |
rebind |
{ build } |
A later handshake agrees again |
transporthost |
{ host: 'page', error } |
The transport worker could not host the descriptor, so your page did |
carrier |
CarrierInfo |
The transport's wisp connection is up, each time it (re)connects |
controller.addEventListener('stale', () => showBanner('An update is installing'));
controller.addEventListener('rebind', () => hideBanner());RemoteController mirrors StompController over postMessage to the hidden controller frame.
Members: proxyOrigin, directory (a string), id, build, config (set once wait() resolves, undefined before), stale, carrier, frames (RemoteFrame[]), isReady, element (the hidden controller <iframe>), cookies, passkeys, shields, siteMode.
Methods, as on StompController: wait(), createFrame(iframe?) (returns a RemoteFrame, sets sandbox and referrerpolicy="no-referrer"), route(url) (a URL on the proxy origin), unroute(url), setTransport(descriptor), setRules(rules), clearCache(), forgetStorage(origin), suggest(text, options?) (asked by the controller frame, see search suggestions), adblockDefaults(), getAdblockLists(), setAdblockLists(lists), refreshAdblockLists().
What it does not have: register(), rebind(), serviceworker, transport, transportHost, hookErrors and the transporthost event.
wait() rejects with an error whose name is 'StorageBlockedError' when the browser gives the controller frame no storage, which happens when the proxy origin is another site and third-party cookies are blocked. See Origin isolation.
Events: navigate ({ info, frame }), open ({ url, frame }), request (the report with a RemoteFrame), hookerror ({ info, frame } for a hook that threw, { info } for a hook URL that failed), stale, rebind and carrier.
Frame is one proxied browsing context, usually one tab. Get it from createFrame().
| Member | Type | What it is |
|---|---|---|
go(url) |
Promise<void> |
Navigates to url through the proxy. Resolves when the new document first reports, 1 s after the frame's load if it never reports (an error page, for example), 30 s at most. The first report comes at document start, so to read the page's DOM, listen for the frame's load before calling go(). |
back(), forward()
|
Promise<boolean> |
Steps the frame's own history, nested frames included, as a tab's Back and Forward do. Never walks your page's history or another frame's. false when there is no entry in that direction. |
reload() |
Promise<boolean> |
Reloads; resolves like go(), false when there was nothing to reload |
canGoBack, canGoForward
|
boolean | null |
Whether back() and forward() have somewhere to go; null when the browser has no Navigation API |
url |
string | null |
The real URL of the proxied page, null when the frame shows none (an error page included) |
title |
string | null |
The last title the page reported |
lastNavigate |
NavigateInfo | null |
The last report |
element |
HTMLIFrameElement |
The frame |
controller |
StompController |
The controller that made it |
Event: navigate, detail is the NavigateInfo.
title and lastNavigate keep the last proxied page's values while an error page shows, because error pages do not report. On a Frame, frame.url === null tells you an error page is up. A RemoteFrame's url stays the URL that failed, so a host using RemoteController has its error page post a message to parent instead (see Embed STomp in your site).
RemoteFrame has go(), back(), forward(), reload(), element, controller and the navigate event, plus:
| Member | What it is |
|---|---|
url, title, canGoBack, canGoForward
|
Plain fields with the last known values, updated by the page's reports and by the poll (pollInterval) |
refresh() |
Asks the controller frame for the current values now |
You cannot read a RemoteFrame's document: it is cross-origin by design.
const frame = controller.createFrame();
document.querySelector('#view').append(frame.element);
frame.addEventListener('navigate', (event) => {
addressBar.value = event.detail.url;
backButton.disabled = event.detail.canGoBack === false;
});
await frame.go('https://example.com/');new SearchBuilder(template) turns what a user typed into a URL. query(input) returns:
-
inputunchanged if it starts withhttp://orhttps://; -
http://+inputif it looks like a host (no spaces and a dot, orlocalhostwith an optional port); - otherwise
templatewith its first%sreplaced byencodeURIComponent(input).
import { SearchBuilder } from '@sysce/stomp';
const search = new SearchBuilder('https://duckduckgo.com/?q=%s');
search.query('example.com'); // 'http://example.com'
search.query('hello world'); // 'https://duckduckgo.com/?q=hello%20world'
await frame.go(search.query(addressBar.value));A bare host gets http://, not https://. If you want HTTPS first, prefix it yourself before calling query().
controller.suggest(text, options?) returns a search engine's completions for what the user typed, the list a browser shows under its address bar. StompController and RemoteController both have it, in builds from 4.2.0-nightly.202611200512.g041dc67 on. It is a method of the controller because the request goes through the controller's transport. The engines' suggest endpoints send no CORS headers, and a request over the relay needs none, so you need no endpoint of your own and your server never sees what the user types.
const completions = await controller.suggest('new york ti', { engine: 'duckduckgo', limit: 4 });
// ['new york times', 'new york times games', 'new york times wordle', 'new york times crossword']| Option | Default | What it does |
|---|---|---|
engine |
'google' |
An id of SEARCH_ENGINES, or the results template of one (the template you gave SearchBuilder, such as 'https://duckduckgo.com/?q=%s') |
endpoint |
none | The suggest URL of an engine not in the list, with %s where the text goes. It must be http: or https:, and it wins over engine
|
limit |
8 |
The most completions returned. Chrome shows 8 at most |
signal |
none | An AbortSignal. Aborting rejects the call at once with the signal's reason, and a late answer is dropped |
It resolves to an array of strings: trimmed, each once, and never the text itself. The text is trimmed, runs of whitespace become one space, and it is cut at 200 characters. Text that is empty after trimming resolves to [] with no request. The endpoint must answer in the OpenSearch suggestions format, [query, [completion, ...]]; an answer in another shape, an empty body or a body over 256 KiB resolves to [] too. Bing's endpoint answered 204 with an empty body when this page was tested, so engine: 'bing' gave [].
It rejects when:
-
engineis neither an id nor a known template, orendpointhas no%sor is nothttp(s): aTypeError, "Stomp: suggest() takes an engine of SEARCH_ENGINES, or an http(s) endpoint with %s for the query".RemoteControllerrejects with a plainErrorwith the same message, because the error's type does not survive the trip back from the controller frame. - The engine answers a status outside 200 to 299: "Stomp: the suggest endpoint answered 429", for example. Up to 3 redirects to
http(s)URLs are followed first. - The transport fails.
-
signalaborts: withsignal.reason, which is anAbortErrorDOMExceptionafter a plainabort().
The request is a GET that the host makes for itself, not one of a proxied page. It carries no cookies at all, neither the engine's nor any proxied page's, and no Origin, no Referer and no storage partition. Its headers are the ones Chrome sends for a request of the browser's own: Sec-Fetch-Site: none, Sec-Fetch-Mode: no-cors, Sec-Fetch-Dest: empty, the browser's User-Agent, Accept-Encoding: gzip, deflate, br, zstd (less when the transport decodes less) and Accept-Language from navigator.languages. The engine sees the text coming from the relay's IP address, with no cookie that ties it to an account.
StompController.suggest() waits for the transport and nothing else: it needs no service worker, and it works before wait() resolves. RemoteController.suggest() is answered by the controller frame, through the transport there, after the frame's handshake. Its signal stays in your page: aborting rejects at once, and the frame's request runs to its end and its answer is dropped.
Brave's endpoint answers 429 to headless Chrome's user agent. Test with another engine, or in a browser with a window.
SEARCH_ENGINES is an array of { id, name, search, suggest }: search is the results template you can give SearchBuilder, suggest the endpoint suggest() asks.
id |
name |
search |
suggest |
|---|---|---|---|
google |
https://www.google.com/search?q=%s |
https://www.google.com/complete/search?client=chrome&q=%s |
|
duckduckgo |
DuckDuckGo | https://duckduckgo.com/?q=%s |
https://duckduckgo.com/ac/?q=%s&type=list |
bing |
Bing | https://www.bing.com/search?q=%s |
https://www.bing.com/osjson.aspx?query=%s |
brave |
Brave | https://search.brave.com/search?q=%s |
https://search.brave.com/api/suggest?q=%s |
startpage |
Startpage | https://www.startpage.com/do/search?q=%s |
DuckDuckGo's, since Startpage publishes no suggest endpoint |
searchEngine(name) returns the entry whose id is name, or whose search template is name up to its %s (the scheme and a leading www. aside), and null for anything else. searchEngine('https://duckduckgo.com/?q=%s') is the DuckDuckGo entry, and searchEngine('https://example.com/?q=%s') is null. suggest() resolves engine the same way.
Both are exported from @sysce/stomp and from @sysce/stomp/omnibox. With classic scripts, read Omnibox.SEARCH_ENGINES.
The omnibox module puts a dropdown of ranked suggestions under any text input: your open tabs, the pages your tabs visited, your bookmarks and the engine's completions from controller.suggest(). The demo's two address bars are built on it. It is plain DOM code with no framework and no CSS of its own. Load it from @sysce/stomp/omnibox (dist/omnibox.mjs) or as the classic script dist/omnibox.js, whose global is Omnibox (see package exports). Embed STomp in your site wires it to a tabbed browser.
attachOmnibox(options) attaches the dropdown to options.input and returns a handle.
| Option | Required | What it is |
|---|---|---|
input |
yes | The <input>. It becomes an ARIA combobox (role, aria-autocomplete, aria-controls, aria-expanded, aria-activedescendant), and the browser's own autocomplete and spellcheck are turned off |
list |
yes | The element the rows go in. It gets role="listbox", and an id if it has none. It is empty while the list is closed, so :empty { display: none } hides it |
search |
yes | The results template, %s the query, as for SearchBuilder
|
toUrl(text) |
no | What the first row opens. Default: new SearchBuilder(search).query(text)
|
engineName |
no | The name in the first row's "Search ... for" text. Default: the SEARCH_ENGINES name of search, else the host of search
|
local(text) |
yes | Your own rows for the text, scored. Build them with tabRows, historyRows and bookmarkRows. It runs on every keystroke |
complete(text, signal) |
no | The engine's completions: controller.suggest(text, { engine, signal })
|
remote(text, signal) |
no | More rows of your own that take a request, asked at the same time as complete
|
picks() |
no | The empty box's rows, { jump?, recentSites, topSites, openTabs }. historyPicks() gives recentSites and topSites
|
typedOnly |
no | Suggest for what was typed since the input got focus, not for the text it already showed. Set it on an address bar that shows the page's URL |
navigate(row) |
yes | Opens a picked row that has a url and no action of its own |
row(row, text) |
no | Draws a row and returns its element. Default: icon, title, subtitle and hint |
header(key) |
no | Draws a group's header, or returns null for none. Default: the text in HEADERS
|
rowClass |
no | The class of the default rows. Default omnibox-row
|
toggled(open) |
no | Called when the list opens or closes |
The handle:
| Member | What it does |
|---|---|
refresh() |
Ranks again while the input has focus, after something a source reads has changed (a tab closed, a bookmark added) |
close() |
Closes the list until the text changes or the input gets focus again. Call it when the form submits |
open |
Whether the list is open |
destroy() |
Removes the module's listeners from the input |
How it behaves:
- The first row always opens what was typed: "Go to ..." when
toUrl(text)is an address, "Search for ..." when it is the search template. Groups follow, ordered by their best row, with at most 3 open tabs, 4 sites (history and bookmarks), 2 pages, 4 completions and 3 rows of any kind of your own, and 10 rows below the first in all. A page open in a tab shows as its tab, not as a site. -
localruns on every keystroke.completeandremoterun 250 ms after the last keystroke, for 2 characters or more, and only when the text is a search (not whentoUrlmakes an address of it). One request runs at a time: new text aborts the one in flight, and an answer for older text is dropped. Until the new answer comes, the last answer's completions that still start with the text stay on the list. - ArrowDown and ArrowUp move the highlight and wrap around the ends. Enter opens the highlighted row; with nothing highlighted, it lets the form submit as before. Tab puts the highlighted row's text in the input (
fill, else its URL, else its title). Escape closes the list. Shift+Delete forgets a row that can be forgotten (a history row, when you givehistoryRowsaforgetfunction). Hovering highlights. The input keeps the focus, and picking a row blurs it. - The empty box shows
picks()once it is clicked or ArrowDown is pressed. Focusing it alone opens nothing, so a new tab page that focuses its box on load shows no list.
The default renderer's classes: omnibox-row (or rowClass) on a row, omnibox-icon on its <img>, omnibox-text, omnibox-sub (the subtitle) and omnibox-hint, and omnibox-head on a header. The highlighted row has a data-hover attribute and aria-selected="true". HEADERS has the header texts ("Open tabs", "Sites", "Pages", "Search suggestions", "Jump back in", "Top sites") and HINTS the hints ("Switch to tab", "Open", "Search"); change them to translate the default renderer.
| Function | Returns |
|---|---|
tabRows(text, tabs) |
"Switch to tab" rows. A tab is { id, url, title?, icon?, activate() }: id stays the same while the tab is open, and activate() switches to it. Tabs whose URL is not http(s) are left out |
historyRows(text, visits, forget?) |
One row per page of the history (visitHistory().visits()), scored by how well it matches and how often and lately it was visited. With forget(url), Shift+Delete removes the page |
bookmarkRows(text, bookmarks) |
Rows for bookmarks { url, title?, icon? }, scored like a page visited often |
historyPicks(visits, openUrls?) |
{ recentSites, topSites } for picks(), leaving out the pages in openUrls
|
safeIcon(icon) |
icon when it is a data:image/ URL or a path on your own origin (/icons/a.png), else undefined
|
Every source passes icons through safeIcon. A site's own icon URL is dropped because an <img> on your page would fetch it straight from the site, outside the proxy (Titles and icons explains).
visitHistory() keeps the pages your tabs reached in the browser's localStorage and nowhere else.
| Option | Default | What it is |
|---|---|---|
key |
'omnibox:visits' |
The storage key. Boxes on one origin with the same key share one history |
cap |
5000 |
The most visits kept, newest first |
store |
localStorage |
Any object with getItem, setItem and removeItem; null keeps nothing |
| Method | What it does |
|---|---|
visits() |
The visits, newest first: { id, url, title, icon?, at }, at in milliseconds since 1970 |
record(tab, { url, title?, icon? }) |
tab (any value that stands for one tab) is on url. A second report of the URL the tab's last visit has updates that visit's title and icon instead of adding a visit, so call it from every navigate report. URLs that are not http(s) are ignored |
forget(url) |
Removes every visit of that page (the same scheme, host without www., path and query) |
clear() |
Removes every visit |
Storage that throws (blocked, or full) keeps no history and raises no error.
A row is a Suggestion: { kind, id, title, subtitle?, icon?, url?, displayUrl?, run?, score, fill?, forget? }. id must be unique among the rows, score orders them (a row with score 0 is dropped), and a row with run calls it instead of navigate. The ranking helpers the sources use are exported for rows you score yourself: matchScore, urlMatch, scoreUrl, recencyWeight, frecentSites, canonicalUrl, hostOf, fold, siteRow, completionRows, defaultRow, rankAndGroup and topPicks.
| Field | Type | Meaning |
|---|---|---|
url |
string |
The real URL the page shows |
title |
string |
The document title |
canGoBack, canGoForward
|
boolean | null |
The frame's history state; null without the Navigation API |
icon |
string | null |
The page's first <link rel="icon"> (or shortcut icon), else its apple-touch-icon, resolved against the real URL. null when it declared none; try /favicon.ico yourself then. |
What onRequest receives, plus frame.
| Field | Type | Meaning |
|---|---|---|
url |
string |
The real URL |
method |
string |
The request method |
destination |
string |
The fetch destination; 'fetch' for fetch(), XHR and beacons |
status |
number |
The status; 0 when the transport failed. A blocking rule reports 403 with kind: 'blocked'
|
ms |
number |
Time in the service worker, from routing to the response headers |
cached |
boolean |
Answered from the HTTP cache without a request |
revalidated |
boolean? |
Answered from the cache after a 304
|
bytes |
number | null |
Content-Length, when known |
error, kind
|
string? |
What failed: kind is transport, timeout, routing, blocked or controller
|
rule |
number? |
The index of the request rule that applied |
rewriteCache |
'hit' | 'miss' | 'skip'? |
For a script: from the rewrite cache, rewritten and kept, rewritten and not kept |
rewriteIn |
'pool' | 'pool split' | 'service-worker'? |
For a script rewritten now: where |
rewriteBy |
'wasm' | 'js'? |
For a stylesheet with URLs or a script rewritten now: whether the wasm module or the JavaScript path wrote the output (the same rewrite either way) |
client, owner
|
string? |
The service worker client that made it, and for a worker the document that made the worker |
frame |
Frame | null |
The frame showing the page the request belongs to |
{ name, value, domain, path, expires, secure, httpOnly, sameSite, hostOnly }. expires is an ISO date or null for a session cookie, sameSite is 'lax', 'strict' or 'none', hostOnly is true for a cookie set without a Domain attribute.
{ phase, kind?, url, message, stack? }, where phase is 'pre', 'post' or 'url' (a hook file that could not be fetched; url is then the hook's URL).
{ carrier, url, ms, why?, previous?, reconnected?, transport?, http3? }: carrier is 'webtransport' or 'websocket', why says why not WebTransport ('off' when the descriptor has no webTransport).
Each config below was run in headless Chrome 157 against master (154de5c9) with epoxy and holyWisp. Swap the wisp URL for your relay's.
Same-origin, every default. Good for trying STomp on your machine.
import { StompController } from '/stomp/controller.mjs';
const registration = await StompController.register('/stomp/');
const controller = new StompController({
serviceworker: registration,
transport: { module: '/epoxy/index.mjs', options: [{ wisp: 'wss://holywisp.fracit.al/' }] },
directory: '/stomp/',
});
await controller.wait();
const frame = controller.createFrame();
document.body.append(frame.element);
await frame.go('https://example.com/');What you get: the xor codec, the HTTP cache, the content blocker on a best effort basis, emulated service workers, rewrite workers for half your cores, and the default sandbox.
Still same-origin, with what a real UI needs: an address bar, an error page, popups to tabs, a request log, rules and a hook.
import { StompController, SearchBuilder } from '/stomp/controller.mjs';
const registration = await StompController.register('/stomp/');
const search = new SearchBuilder('https://duckduckgo.com/?q=%s');
const controller = new StompController({
serviceworker: registration,
transport: {
module: '/epoxy/index.mjs',
options: [{ wisp: 'wss://holywisp.fracit.al/' }],
},
directory: '/stomp/',
codec: 'xor',
errorPage: '/error.html',
rules: [
{ match: { url: '*://*:*/ads/*' }, action: 'block' },
{
match: { url: 'https://api.example.com/*' },
action: { requestHeaders: { 'x-from-host': 'my-app' } },
},
],
hooks: {
init: {
post: { source: "if (stomp.isTop) console.log('hook in', stomp.url)" },
},
},
onNavigate(info, frame) {
updateTab(frame, info); // your UI: address bar, title, icon, buttons
},
onOpen(url, frame) {
openTab(url); // your UI: a new frame, then frame.go(url)
},
onRequest(info) {
logRequest(info); // your UI: a per-tab log keyed on info.frame
},
onHookError(info) {
console.warn('hook failed', info);
},
});
controller.addEventListener('stale', () => showUpdateBanner());
await controller.wait();
const frame = controller.createFrame();
document.querySelector('#tabs').append(frame.element);
await frame.go(search.query(addressBar.value));Embed STomp in your site builds the tab UI around this.
For production: the proxy on its own origin, the host locked in, invalid scripts loud, the default sandbox, client left unset.
import { RemoteController } from '/stomp/controller.mjs';
const controller = new RemoteController({
proxyOrigin: 'https://proxy.example.com', // your second origin, same site as your page
directory: '/stomp/',
transport: { module: '/epoxy/index.mjs', options: [{ wisp: 'wss://holywisp.fracit.al/' }] },
codec: 'xor',
errorPage: '/error.html', // served by the proxy origin
allowInvalidJs: false,
rules: [{ match: { url: '*://*:*/ads/*' }, action: 'block' }],
onOpen(url, frame) {
openTab(url);
},
onRequest(info) {
logRequest(info);
},
});
try {
await controller.wait();
} catch (error) {
if (error.name === 'StorageBlockedError') showThirdPartyCookieHelp();
throw error;
}
const frame = controller.createFrame();
document.querySelector('#tabs').append(frame.element);
await frame.go('https://example.com/');On the proxy origin, set the allowed host in the controllerFrame.html you serve:
<meta name="stomp-allowed-origins" content="https://app.example.com" />With this setup the host page cannot read the proxied document (frame.element.contentDocument is null), the service worker sends frame-ancestors https://app.example.com on proxied documents, and a page from another origin cannot drive the controller frame. allowInvalidJs: false is a judgment call: it surfaces rewriter failures as SyntaxErrors instead of running unrewritten code. Deploy STomp covers the headers, HTTPS and caching that go with it.
Your directory is missing core.wasm or rewriterLib.js, or you renamed them without telling assets. Serve all of dist/. An answer with Content-Type: text/html counts as missing, so a single-page-app fallback that returns index.html for unknown paths shows up here too.
The controller frame refused your page. Check that stomp-allowed-origins in the controllerFrame.html you serve lists your page's exact origin (scheme, host and port), or is empty. Also check that proxyOrigin serves <directory>controllerFrame.html.
A URLPattern string without a port matches default ports only, so *://*/ads/* misses http://127.0.0.1:9311/ads/x.js; write *://*:*/ads/*. https://*.example.com/* does not match https://example.com/. For fetch() and XHR, match destination: ['empty'], not 'fetch'. A rule with a url needs URLPattern (Chrome, Edge): look for "request rule skipped" on the console.
The controller frame takes your origin from document.referrer. A host page with Referrer-Policy: no-referrer gives it none, and the frame stops with "Invalid URL" on its console. Send strict-origin-when-cross-origin (the browser default), strict-origin or origin on the host page.
register() and the constructor fell back to your page's directory because you passed none. Pass directory to both.
Error pages do not report. On a Frame, frame.url is null then; a RemoteFrame keeps the URL that failed.
The helper names are minted per host origin; DEFAULT_NAMES are only fallbacks. Read controller.config.names for the names in use.
An invalid id, names or hooks value. The message names the field.
The text was empty after trimming, or the engine answered with no completions list. Bing's endpoint has answered 204 with an empty body; try another engine. A 429 rejection from Brave in a test run is its answer to headless Chrome's user agent.
Pass a descriptor when controller.transportHost is 'worker' and an instance when it is 'page'.
More symptoms are on the Troubleshooting page.
STomp is licensed under the GPL-3.0. Found a mistake in these pages? Open an issue.