Merchants configure a customer-facing e-commerce support app from an older Angular admin: which sections appear on each page, in what order, with what colours. The editor needed a preview. A mock of the customer app inside the admin would drift from the real thing within a release, so the admin embeds the real React app in an iframe and drives it over postMessage.
The same React build already ran standalone on its own domain and as a widget framed inside a storefront page. The preview could not break either.
Three modes, one predicate each
Most embed bugs came from code written for one mode and silently applied to another. So each mode has exactly one question that identifies it.
- Storefront embed. Framed, no extra URL parameters. The app measures its own content and posts its height so the host page can size the frame. Header and footer are hidden.
- Host preview. A URL parameter says a host is present. Only its presence is read, never its value, and it flips every default: the host sizes the frame, header and footer are shown.
- Editor preview. A separate query parameter. No API calls, fixtures for data, and a message bridge to the editor.
"Am I in an iframe?" is true for all three, so it never gates mode-specific behaviour. The editor mode is read once at load, because the router drops the query string on navigation:
const previewType = readPreviewParam(window.location.search)
if (previewType != null) {
document.documentElement.classList.add('is-preview')
}
export function isEditorPreview(): boolean {
return previewType != null
}
The envelope
Every message in both directions has the same shape: a source tag, a sequence number, a type and a payload.
interface Envelope {
source: 'editor-host' | 'editor-preview'
seq: number
type: string
payload: unknown
}
Payloads are typed per message type, so a handler receives the right shape without a cast.
The host sends init, config, theme, page, device, select and hover. The preview answers with ready, navigate, select, reorder, add and delete requests, and history for undo and redo.
This protocol has a sequence number, not a version handshake. The message enums live in the React repo and are copied by hand into the Angular one. A message added on one side and not the other is silently ignored. What I have instead of a shared package is a test file that feeds the React listener envelopes shaped exactly as the Angular service builds them, so drift fails a test instead of producing a dead preview.
The preview applies some changes optimistically, such as a drag reorder, and tells the host. The host then echoes its new state back. Without ordering, a late echo of an older state overwrites the newer one and the two sides ping-pong. The preview tracks the last sequence it applied and drops anything older.
Origin checks
The listener rejects a message unless all of these hold:
- the source tag is the host's,
event.sourceiswindow.parent,- the origin's hostname ends with an allowed suffix (localhost only in development builds),
- the type is a known message type.
The first message that passes pins the origin. After that, only that exact origin is accepted, and outgoing messages target it explicitly.
let hostOrigin: string | null = null
function accept(event: MessageEvent): boolean {
if (event.source !== window.parent) {
return false
}
if (hostOrigin != null) {
return event.origin === hostOrigin
}
return isAllowedOrigin(event.origin)
}
Before the pin exists, the preview has to announce ready to an unknown parent, so that one message goes to '*'. If the host was not listening yet, it sends a hello ping and the preview announces again.
Zero API calls in preview
The editor preview must render without a session, a customer or a backend. The app has exactly one HTTP client instance, which made this a single swap: in preview mode its adapter is replaced with one that answers from a table of fixture routes.
type Route = [RegExp, (req: PreviewRequest) => unknown]
function createPreviewAdapter(routes: Route[]): AxiosAdapter {
return async config => {
const req = toRequest(config)
for (const [pattern, resolve] of routes) {
if (pattern.test(req.url)) {
return ok(config, await resolve(req))
}
}
if (import.meta.env.DEV) {
console.warn(`[preview] unmatched ${req.method} ${req.url}`)
}
return ok(config, [])
}
}
Because the swap is at the client, it covers call sites that do not exist yet. An unmatched request resolves empty and warns in development.
Preview mode also skips the WebSocket, error reporting, query persistence and the per-brand stylesheets, and backs the persisted store with in-memory storage, so nothing is written to localStorage.
All preview-only code sits behind a dynamic import, so customers never download it. That created a race: a host message can arrive before the module has subscribed. The bridge holds the latest undelivered message per type and replays it on subscribe. Config and theme messages are also coalesced into one animation frame.
Clicks do not mean what they usually mean
In the editor, a click on a section should select it, not run it. The preview installs a capture-phase listener that swallows click, pointer, submit and keydown events, then reports which section was hit. I did not use pointer-events: none, because that takes scrolling with it.
Three exceptions pass through: the preview's own add and drag handles, an allowlist of harmless controls such as accordion toggles and carousel arrows, and navigation links when the editor's navigation toggle is on. Log out is deliberately excluded: it would end the fake session and blank the frame.
Swallowing keydown broke undo. With focus inside the frame, the shortcut never reached the editor, which owns the history. The preview now detects the shortcut and relays it as a message.
Pitfalls I hit
Session and URL desync. The app has several top-level experiences with their own route trees. Hardcoded navigation left sessions of one kind on another kind's route, where they rendered inert buttons and never recovered. The fix was a registry that maps a session to its home path, and a route guard that redirects when URL and session disagree.
Theme staleness. Theme variables were memoized on object identity. Patching the config in place updated text but left colours stale. Every patch from the editor now builds a new object, with a regression test.
Paint before config. Fixture defaults rendered first, then snapped to the merchant's config. The preview now waits for the first real config before navigating, with a timeout.
100vh in a self-sizing frame. In the storefront embed, vh is the height last reported to the host. A max-height: 90vh can never grow the frame that caps it. Every CSS rule that removes such a constraint for the self-sizing mode needs a paired rule restoring it for the host-sized mode.
Takeaways
- Give each embed mode one predicate and never gate on "is framed".
- Put a source tag and sequence number on every message. Add a version too; I did not, and a mirrored test is the workaround.
- Check
event.source, allowlist the origin, then pin it. - If there is one HTTP client, swapping its adapter is the cheapest way to guarantee no network calls.
- Lazy-load preview code and replay messages that arrive before it subscribes.
- Swallowing events in the capture phase also swallows the keyboard shortcuts the host needs. Relay them.