Field guideGuideCC BY 4.0 licensed

Embed Field Guide

Responsive iframes and honest browser boundaries

A practical one-page guide to the parts of third-party embeds that fail in production: intrinsic height, resize feedback loops, cross-frame messages, framing policy, and what “same-origin security” does—and does not—mean.

2
documents in every embed
3
approved lifecycle events
360–900px
default height clamp
0
form answers sent to the host

Role

Research, implementation, and browser testing

Built with

  • iframes
  • postMessage
  • ResizeObserver
  • Content Security Policy

The architecture that held up

We built forms and booking flows as a small loader script that registers purpose-named custom elements such as <product-form> and <product-booking>. Each element creates an iframe pointing back to the application. The iframe owns application logic, browser storage, signatures, and submission; the host owns placement and width; a narrow message contract connects the two.

The custom element is the integration API, not the security boundary. It gives customers readable markup, sensible defaults, validated attributes, lifecycle events, and one place to evolve compatibility. The iframe supplies the browser boundary. This follows the established shape used by products such as Cal.com, Typeform, and YouTube: a small host-side API around a vendor-origin iframe, with messages for the few things that must cross the boundary. The exact API differs—YouTube does not expose a custom element—but the architectural seam is proven and familiar.

This was not just a convenient wrapper. Application code could keep using its existing same-origin data layer while the customer website stayed unable to read the iframe DOM, fields, or storage. Patient answers remained out of the host page and its third-party scripts.

The important qualification is that same-origin is not, by itself, a security property. The iframe is same-origin with the application but normally cross-origin from the host. That boundary does not make a public form private, authenticate its visitor, or stop someone from copying the embed elsewhere.

Host page: the custom element is the public API

<script src="https://app.example.com/embed.js" async></script>
<product-form
  account="acme"
  form="intake"
  height="360,900"
  theme="auto"
></product-form>

Responsive height is a protocol

Width is ordinary responsive CSS: the iframe fills the space its host provides. Height crosses a document boundary, so the parent cannot inspect the child and CSS alone cannot solve it. Our first fixed 640px frame failed in both directions—empty space around short questions and an inner scrollbar on signatures and terms.

Measure natural content
Embedded mode removes viewport sizing such as min-height: 100dvh. A ResizeObserver watches the content root and posts a numeric height; a low-frequency polling fallback covers browsers where the observer is unavailable or throws.
Bound the movement
The parent clamps reports to 360–900px by default and animates changes over 200ms, with fixed height and custom min,max options. A skeleton occupies the minimum before the first useful measurement and respects reduced-motion preferences.
Break the feedback loop
The real bug was a measured screen that could shrink to its fixed-height flex parent. It reported the frame’s current height back and could never grow. Making that screen content-sized with flex: none fixed it. Never measure a node whose size is derived from the iframe viewport you are about to resize.
Test behavior, not a screenshot
Cover narrow hosts, short and tall steps, validation errors, keyboard navigation, slow or blocked loads, reduced motion, and both growth and shrinkage. Disable embedded autofocus when it can unexpectedly scroll the host page.

Child: report intrinsic height

const root = document.querySelector("[data-embed-root]");
let lastHeight = 0;

const reportHeight = () => {
  const height = Math.ceil(root.getBoundingClientRect().height);
  if (height > 0 && height !== lastHeight) {
    lastHeight = height;
    window.parent.postMessage({ type: "embed:resize", height }, "*");
  }
};

new ResizeObserver(reportHeight).observe(root);
reportHeight();

A narrow message contract

The child reports readiness, successful completion, and a number for height—never form answers or guest details. The parent accepts a message only when event.origin is the application origin and event.source is that exact iframe window, then re-dispatches an approved event for host analytics or navigation.

The child uses targetOrigin "*" because the same embed can appear on arbitrary customer domains. That is defensible only while outbound messages are non-sensitive. The moment a payload includes personal or booking data, the design needs an allow-listed parent origin and a different trust model.

Parent: validate before resizing

const appOrigin = new URL(iframe.src).origin;

window.addEventListener("message", (event) => {
  if (event.origin !== appOrigin) return;
  if (event.source !== iframe.contentWindow) return;
  if (event.data?.type !== "embed:resize") return;

  const height = Number(event.data.height);
  if (!Number.isFinite(height)) return;
  iframe.style.height = Math.min(900, Math.max(360, height)) + "px";
});

Scope the framing exception

Embeddable pages must allow another site to frame them; authenticated application pages should not. Our default is Content-Security-Policy frame-ancestors 'self', with X-Frame-Options: SAMEORIGIN as a legacy counterpart. Only dedicated embed routes omit that restriction. Before that split, staff pages were frameable too—a clickjacking exposure created by making the whole site convenient for one feature.

Host customization is a validated set of values—theme, colors, radius, and font—not arbitrary CSS or markup. An iframe is a useful isolation boundary only while neither side quietly installs a tunnel through it.

Next.js: protect everything except embed routes

export default {
  async headers() {
    return [{
      source: "/:path((?!embed(?:/|$)).*)",
      headers: [
        { key: "Content-Security-Policy", value: "frame-ancestors 'self'" },
        { key: "X-Frame-Options", value: "SAMEORIGIN" },
      ],
    }];
  },
};

What localhost will not tell you

Third-party cookies and storage vary by browser. Embedded localStorage is commonly partitioned by top-level site, so a draft on a practice website may not appear on the direct application link. Two localhost ports are still the same site for cookies, which can make a development embed look authenticated when a production cross-site embed will not be.

Use genuinely different hostnames and include Safari and Firefox in the test matrix. Same-origin with the application preserves application capabilities; it does not replace rate limits, payload limits, authorization on private routes, clickjacking policy, or sensitive-data-safe logging.

The takeaway

Treat an embed as a small distributed system: two documents, a versioned message contract, an explicit trust boundary, and browser-dependent storage behavior. Keep the data flow minimal, validate both ends of every message, measure intrinsic content, scope framing exceptions to dedicated routes, and test on a genuinely different site before calling the result secure or responsive.