Iframe Quickstart
Start with a read-only runtime iframe. Your page sends supported postMessage requests to Chastify's parent window, which makes authenticated reads on the user's behalf. State writes, runtime file uploads, and lock actions need your backend and the credentials described in Developer API Overview.
Create the extension with a main iframe URL and a setup iframe URL, then install it on a test lock. See Extension Release & Beta Testing for developer/tester access. Opening your hosted URL directly does not provide a Chastify session.
What Chastify Passes To Your Iframe
The parent replaces the URL fragment with URI-encoded JSON. Parse it with JSON.parse(decodeURIComponent(location.hash.slice(1))) or the helper below. Do not use that fragment for your own hash router without preserving the launch context.
| Field | Purpose |
|---|---|
bridge.v | Bridge protocol version, currently 1. |
bridge.nonce | Identifies the current iframe launch for outgoing requests. It is browser-visible, not a signature or backend secret. |
bridge.parentOrigin | Exact target origin for messages to the parent. |
appId, sessionId, lockId | Application, installed extension session, and lock identifiers. These are different IDs. |
ui | Initial theme values. |
homeActionSlug, homeAction, intent | Optional context for opening a specific extension action. |
regularActionsSummary | Optional launch-time snapshot; read current status before relying on it. |
mainToken | Optional short-lived launch token for forwarding to your backend. It is insufficient by itself for backend mutations. |
Re-read the payload on a new launch. Do not persist a nonce or mainToken as a permanent credential, and do not log or share the complete launch fragment.
Quick Start With The Bridge Library (Recommended)
The repository includes a sample helper at apps/extension/src/lib/ChastifyBridge.ts; it is not a separately installed SDK package. Reuse it in the sample extension or copy/adapt it into your own project, adjusting import paths.
It provides parseHashPayload, ChastifyBridgeClient, startAutoResizeToParent, and themeVars. Requests reject on a bridge error or after a default 15-second timeout. Handle those failures in your UI and call destroy() when disposing of the client.
Minimal React bootstrap
This browser-side example reads context when you select Load context, handles errors, receives theme changes, and cleans up listeners. It expects the usual <div id="root"> mount element.
import { useEffect, useState } from "react";
import {
parseHashPayload,
ChastifyBridgeClient,
startAutoResizeToParent,
themeVars,
type UiSkinV1,
} from "../lib/ChastifyBridge";
const payload = parseHashPayload();
if (payload?.mode === "setup" || payload?.bridge?.v !== 1 ||
!payload.bridge.nonce || !payload.bridge.parentOrigin) {
throw new Error("Open this runtime page from a Chastify lock");
}
const { nonce, parentOrigin } = payload.bridge;
const initialUi = payload.ui ?? null;
export function App() {
const [client, setClient] = useState<ChastifyBridgeClient | null>(null);
const [ui, setUi] = useState<UiSkinV1 | null>(initialUi);
const [context, setContext] = useState<unknown>(null);
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const vars = themeVars(ui);
useEffect(() => {
const bridge = new ChastifyBridgeClient({ nonce, targetOrigin: parentOrigin });
setClient(bridge);
const stopResize = startAutoResizeToParent({ nonce, targetOrigin: parentOrigin });
const onMessage = (event: MessageEvent) => {
if (event.source !== window.parent || event.origin !== parentOrigin) return;
const msg = event.data;
if (msg?.type !== "chastify:ext:ui" || msg.v !== 1 || msg.nonce !== nonce) return;
if (msg.ui && typeof msg.ui === "object") setUi(msg.ui);
};
window.addEventListener("message", onMessage);
return () => {
window.removeEventListener("message", onMessage);
stopResize();
bridge.destroy();
};
}, []);
async function loadContext() {
if (!client) return;
setLoading(true);
setError("");
try {
const [session, state] = await Promise.all([
client.request("session.get", {}),
client.request("state.get", {}),
]);
setContext({ session, state });
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Could not load context");
} finally {
setLoading(false);
}
}
return (
<main style={{ background: vars.pageBg, color: vars.text,
colorScheme: vars.isDark ? "dark" : "light", padding: 16 }}>
<h1>Extension Quickstart</h1>
<button disabled={!client || loading} onClick={loadContext}>
{loading ? "Loading…" : "Load context"}
</button>
{error && <p role="alert">{error}</p>}
<pre style={{ whiteSpace: "pre-wrap", overflowWrap: "anywhere" }}>
{JSON.stringify(context, null, 2)}
</pre>
</main>
);
}
The context dump is useful during development. Before release, replace it with the fields your UI needs and respect the response's visibility settings.
Raw postMessage Example (No Helper Class)
For a small integration, you can implement a read directly. This example uses nonce and parentOrigin from the validated launch payload above. Register the response listener before sending, correlate the request ID, and remove the listener on success, error, or timeout.
function readSession(): Promise<unknown> {
return new Promise((resolve, reject) => {
const id = crypto.randomUUID();
const cleanup = () => {
clearTimeout(timer);
window.removeEventListener("message", onMessage);
};
const onMessage = (event: MessageEvent) => {
if (event.source !== window.parent || event.origin !== parentOrigin) return;
const msg = event.data;
if (msg?.type !== "chastify:ext:resp" || msg.v !== 1 || msg.id !== id) return;
cleanup();
if (msg.ok) resolve(msg.data);
else reject(new Error(msg.error?.message || msg.error?.code || "Bridge error"));
};
const timer = window.setTimeout(() => {
cleanup();
reject(new Error("bridge_timeout"));
}, 15_000);
window.addEventListener("message", onMessage);
window.parent.postMessage({
type: "chastify:ext:req", v: 1, id, nonce,
action: "session.get", payload: {},
}, parentOrigin);
});
}
Ordinary bridge responses have type, v, id, and ok, with data or error. They do not echo the nonce. Theme and setup messages use their own nonce checks.
Test Flow You Should Run First
Start with session.get, then state.get and metadata.get. Try regularActions.get only when that feature is enabled. The runtime bridge supports:
| Action | Payload |
|---|---|
session.get, state.get, metadata.get, regularActions.get | {} |
files.capabilities, files.list | {} |
files.get | { "fileId": "stored-file-id" } |
Unsupported actions return unknown_action. Sending state.patch, lock.applyTime, or a backend endpoint name through this bridge does not perform a write. See API Examples for backend request bodies.
Setup uses a separate protocol
A setup launch has mode: "setup", appId, slug, bridge, and ui; it is not a runtime session launch. Register listeners, then send chastify:ext:setup:ready with v: 1 and the current nonce. The parent replies with chastify:ext:setup:init, containing saved config and context.
Send chastify:ext:setup:config with the current configuration when it changes and when the parent sends chastify:ext:setup:get_config. This updates the parent's draft; the user still needs to save the Chastify configuration. Preserve fields you do not own instead of replacing the entire draft with only your new setting.
Use the sample SetupPage.tsx for the configuration flow and Extension File Storage for chastify:ext:setup:req file operations. The runtime ChastifyBridgeClient does not implement that setup request channel.
File Uploads From Iframe
Runtime file upload and deletion belong on your backend. The runtime bridge can inspect capabilities, list files, and refresh a file's signed URL:
const { items } = await client.filesList();
if (items.length > 0) {
const { file } = await client.filesGet(items[0].id);
image.src = file.signedUrl;
}
This snippet assumes an initialized client and your image element; catch request errors as in the bootstrap example. Store stable file IDs in configuration/state, not signed URLs. Re-read a file to obtain a fresh URL when needed.
client.filesCapabilities() reports upload availability and policy. Disabling uploads does not itself disable reading existing files, so do not hide stored files solely because capabilities.enabled is false.
The setup bridge can stage files before a lock session exists. Use its separate message envelope and save the required file references in configuration. There is no runtime client.filesUpload() helper. See Extension File Storage for both workflows.
Theme Support (ui + themeVars)
themeVars(ui) supplies pageBg, text, panel, border, muted, inputBg, and isDark. Apply the background with CSS background, since it can be a complete CSS background value.
Live theme updates
The parent can send chastify:ext:ui with v: 1, the current nonce, and a new ui. Check the parent window, origin, version, and nonce before updating local theme state, as shown above. Use the current state when calculating colors rather than memoizing only the original hash values.
See Iframe Theming for CSS variables, React styling, and light/dark examples.
Auto Resize Support
Call startAutoResizeToParent after your #root element mounts and call its returned cleanup function when disposing of the page. The helper observes that element and sends chastify:ext:resize; it does not send a request requiring a response.
The parent caps iframe height at 4,000 pixels. Resizing helps fit content within that limit but does not guarantee that all scrolling disappears. Avoid sizing the observed content only to the current iframe viewport, which can prevent it from shrinking after sections collapse.
Common mistakes
- Opening the hosted page directly instead of from an installed extension.
- Using a stale nonce or the wrong
bridge.parentOrigin. - Forgetting to allow the hosted iframe's exact origin in the application's Allowed origins, including its port when relevant.
- Reusing the URL fragment for client-side routing and losing the launch payload.
- Using the runtime bridge inside setup or requesting unsupported writes.
- Treating
mainTokenor browser-reported progress as a trusted backend result. - Forgetting client, theme-listener, or resize cleanup on unmount.
For a timeout, first confirm the iframe finished loading and the origin settings match. Retrying a read is different from repeating a backend mutation after an uncertain response; inspect the outcome before repeating writes.
Reference Files
The repository's working examples are:
apps/extension/src/lib/ChastifyBridge.ts— runtime reads, hash parsing, theme tokens, and resize helper.apps/extension/src/pages/MainPage.tsx— runtime UI and calls to an extension backend.apps/extension/src/pages/SetupPage.tsx— configuration messages and setup file staging.
Continue with Developer API Overview, API Examples, and Extension Release & Beta Testing.