SSyncropel Docs

Your First Iframe Extension

In 30 minutes, go from npm create vite to a working iframe extension that connects to a host, writes records and shows live updates. Built with @syncropel/extensions and a small reference host.

This tutorial assumes you've completed Your First SDK Integration. It uses the reference iframe host snippet as the outer page, so you can run it end to end without a full host app.

What you'll build

A small Vite + TypeScript app that runs inside an iframe, completes the handshake with its host, lets the user click a button to write a record through the host, and shows any record updates the host sends.

Every embeddable Syncropel surface has this shape: page widgets, IDE side panels, in-app inspectors, dashboards. Same protocol, same SDK, same security model.

Total time: about 30 minutes, split into five short sections.

Section A: Scaffold the extension (5 minutes)

npm create vite@latest my-ext -- --template vanilla-ts
cd my-ext
npm install
npm install @syncropel/extensions

Open src/main.ts and replace the contents with:

import { createAdapter, type SAPCapability } from "@syncropel/extensions";

const root = document.querySelector<HTMLDivElement>("#app")!;
root.innerHTML = `
  <main style="padding:1rem;font-family:system-ui;">
    <h2 style="margin:0 0 .25rem">My first extension</h2>
    <p id="status" style="color:#666;font-size:.85rem">connecting…</p>
    <button id="emit-btn" disabled>Emit a record</button>
    <h3>Live records</h3>
    <ol id="record-list" style="font-size:.85rem"></ol>
  </main>
`;

const status = document.querySelector<HTMLElement>("#status")!;
const emitBtn = document.querySelector<HTMLButtonElement>("#emit-btn")!;
const recordList = document.querySelector<HTMLElement>("#record-list")!;

const requested: SAPCapability[] = [
  "records.emit",
  "records.query",
  "records.subscribe",
];

const adapter = createAdapter({
  ext: { name: "MyExt", version: "0.1.0", publisher: "my-org" },
  capabilities: requested,

  onInit: ({ actor, namespace, capabilities_granted }) => {
    status.textContent =
      `ready as ${actor} in ${namespace} ` +
      `(granted: ${capabilities_granted.join(", ") || "none"})`;
    emitBtn.disabled = !capabilities_granted.includes("records.emit");
  },

  onRecords: ({ records }) => {
    for (const r of records) {
      const li = document.createElement("li");
      li.textContent = `${r.act} — ${JSON.stringify(r.body).slice(0, 80)}`;
      recordList.prepend(li);
    }
  },

  onGoodbye: ({ reason }) => {
    status.textContent = `goodbye: ${reason}`;
    emitBtn.disabled = true;
  },
});

emitBtn.addEventListener("click", async () => {
  const result = await adapter.emit({
    act: "DO",
    body: {
      kind: "core.action",
      description: "User clicked the button at " + new Date().toISOString(),
    },
  });
  status.textContent =
    result.status === "ok"
      ? `emitted ${String(result.result?.record_id).slice(0, 12)}…`
      : `emit failed: ${result.error?.message ?? "unknown"}`;
});

// Tell the host how tall to make the iframe.
adapter.setHeight(document.body.scrollHeight);
new ResizeObserver(() => adapter.setHeight(document.body.scrollHeight)).observe(
  document.body,
);

Start the dev server:

npm run dev

Vite serves it at http://localhost:5173. Open the URL in a browser. The page renders, but status reads connecting… forever and the button stays disabled. That's expected: there is no host yet.

Section B: The handshake (5 minutes)

The Syncropel host-to-extension protocol is a small four-message exchange:

DirectionKindWhen
host → exthelloHost sends as soon as the iframe load event fires. Carries actor, namespace, selection, and the host's policy-granted capabilities.
ext → hostreadyExtension confirms protocol version and lists requested capabilities.
host → extaction.resultHost's reply confirming the final capability grant.
host → extcontext.update / records.update / goodbyeLifecycle events thereafter.

Origin checks happen on both sides. The host validates the iframe origin against an allowlist before sending hello. The extension records the host's window and origin from the first message it receives and posts back to that origin only. The SDK handles both halves of the validation; you don't write the checks yourself.

Whether the iframe is sandboxed with allow-same-origin depends on the host, so the SDK posts replies to any origin and lets the host match them to the right window. This is the standard postMessage pattern for iframes; see the host snippet for the matching outer-page code.

Section C: Wire up the reference host (10 minutes)

For a working end-to-end demo you need a host page. Copy the reference host snippet into host.html next to your package.json:

# from inside my-ext/
cp /path/to/iframe-host-snippet.html host.html  # or paste from the docs page

Edit three things in host.html:

  1. Set the EXT_URL constant near the top to your Vite dev server URL:

    const EXT_URL = "http://localhost:5173/";
  2. Set the DAEMON_URL to your local Syncropel instance:

    const DAEMON_URL = "http://localhost:9100";
  3. Paste your bearer token (from ~/.syncro/token) into the DAEMON_TOKEN constant.

Serve the host page from a different port so the origin separation is real:

npx serve -l 4173 .

Open http://localhost:4173/host.html. The host page loads, you see the Vite extension inside an <iframe>, the handshake completes, and the status line changes to:

ready as did:example:my-app in default (granted: records.emit, records.query, records.subscribe)

The button is now enabled.

Section D: Write and verify (5 minutes)

Click Emit a record a couple of times. Each click shows a confirmation in the status line:

emitted 9f8e7d6c5b4a…

In a separate terminal, watch the records flow into the instance:

spl thread records <th-from-host> -o json | jq '.data[] | {clock, act, body}'

Replace <th-from-host> with the thread the host snippet selected when it started (the snippet logs it on the host page).

You should see:

{ "clock": ..., "act": "DO", "body": { "description": "User clicked the button at 2026-04-21T...", "kind": "core.action", ... } }

The DID on the records is did:example:my-app, the actor the host named in the hello message, not the extension itself. Extensions never act as themselves; they act as the host's signed-in user. The host's permissions decide what records the user may write, and the extension gets only that for the session.

Section E: Subscribe to live updates (5 minutes)

So far the extension only writes. Now make it react to live record changes too.

In src/main.ts, after the createAdapter call, add:

// Subscribe to records on the same thread the host selected.
let subId: string | null = null;
window.addEventListener("DOMContentLoaded", async () => {
  // Wait one tick for the handshake to complete.
  await new Promise((r) => setTimeout(r, 100));
  if (!adapter.capabilities.includes("records.subscribe")) return;

  const result = await adapter.subscribe({
    where: { act: "DO" },
    limit: 50,
  });
  if (result.status === "ok") {
    subId = String(result.result?.subscription_id ?? "");
    console.log("subscribed:", subId);
  }
});

Reload the iframe. Every time you click the button, the new record appears at the top of the Live records list because the onRecords callback fires from the subscription.

Open another terminal and write a record by hand with the SDK or CLI:

spl do "manual emit" --thread <same-th>

It shows up in the iframe within a second. The extension now takes part in the thread live, instead of only writing to it.

When the user navigates away, clean up:

window.addEventListener("beforeunload", () => {
  if (subId) adapter.unsubscribe(subId);
  adapter.destroy();
});

What you have now

A working iframe extension that:

  • ✅ Completes the host handshake via @syncropel/extensions
  • ✅ Renders inside any host that implements the matching protocol
  • ✅ Requests capabilities the host's policy can grant or deny
  • ✅ Writes records as the host's signed-in actor
  • ✅ Subscribes to live record updates and renders them
  • ✅ Reports its content height for proper iframe sizing
  • ✅ Cleans up subscriptions on unload

Every published extension has this same shape, whether it is a one-button demo or a large app.

What's next

  • Ship it: the Extension publishing playbook covers naming, hosting, capability declarations and security expectations.
  • Embed it in your own product: the reference iframe host snippet is about 200 lines of plain JavaScript you can drop into any web app.
  • Deeper SDK reference: the Extensions SDK guide has the full capability table, message formats and how messages are validated.
  • Build a richer UI: React Components has 21 components you can use inside the extension.
  • Render UI defined on the server: Projections lets the host hand the extension a UI document instead of raw records.

On this page