AI summary

Your embed script runs on someone else's site. When I'd use Shadow DOM, when I'd use a cross-origin iframe, and what each one still lets through.

  • Shadow DOM keeps the page's CSS selectors out, but styles can still pass down from parent elements. Sizes based on the page’s root font size and the page’s JavaScript still affect the embed.
  • A cross-origin iframe is the option to use when the site's own scripts must not read what's inside.
  • You can combine them: the popup in Shadow DOM, with an iframe only for the sensitive step.

The script works on your test page. Then someone adds it to a site with a global button rule, and your layout changes.

At Popupsmart I worked with the team on the Preact runtime that shows popups on customer sites. By runtime I mean the embed script a customer adds to their site. A lot of that work was making the runtime behave on sites we didn’t control, because their CSS, other scripts and loading order could all affect it. I’ll call the customer’s page the host page, or just the host.

Shadow DOM and iframes both help with that, but they protect different things.

Shadow DOM puts your elements in a separate tree, the shadow tree, attached to one element on the page. The root of that tree is the shadow root. It protects styles: the page’s CSS selectors stay out, and its scripts can still get in.

An iframe loads a separate document inside the page. If it comes from a different origin, meaning a different domain, protocol or port, it’s a cross-origin iframe. Besides keeping the page’s CSS out, a cross-origin iframe stops the page’s scripts from reading what’s inside.

What Shadow DOM keeps out

Press “Apply host CSS” in this demo. The same host rule changes the regular button and leaves the one inside the shadow root alone.

Try CSS isolationThe same host rule reaches a regular button, but not the button inside a shadow root.
Regular DOM
Shadow DOM

Host rule is off.

Host selectors don’t match inside your shadow tree, and your styles don’t leak out. The page can still reach you in a few ways:

  • Inherited properties such as color and font cross the boundary. Put all: initial on :host to start clean, then set display after it, because that reset makes the element inline.
  • rem follows the root element. If the host sets html { font-size: 62.5% }, anything you sized in rem shrinks. I’d use px or your own CSS variable.
  • Your elements still sit in the host’s stacking order, so a high z-index on the page can cover them.
  • Your code runs in the host’s page, with its global variables and its Content-Security-Policy.
  • Host scripts can read an open shadow root through shadowRoot. Closed mode, attachShadow({ mode: "closed" }), hides that property, but MDN says not to treat it as a strong security mechanism.

Gainsight’s community platform uses Shadow DOM for custom widgets. A customer writes a widget in HTML, CSS and JavaScript, and Gainsight’s developer docs say it runs inside a custom element, <gs-cc-registry-widget>, that uses Shadow DOM. Each widget gets its own shadow root, so its styles stay out of the community page and out of the other widgets.

The same docs note that document.querySelector() can’t reach the widget’s elements. You go through the custom element’s shadowRoot instead, the same property the last point says host scripts can read.

Here’s a separate example of how to mount a Preact widget in a shadow root with Vite.

tsx
import { render } from "preact";
import { Popup } from "./Popup";
// Vite: ?inline imports the CSS file as a string.
import css from "./popup.css?inline";

const host = document.createElement("div");
document.body.append(host);

const shadow = host.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = css; // Starts with :host { all: initial; display: block; }

// Give Preact its own node so it can't touch the style element.
const mount = document.createElement("div");
shadow.append(style, mount);
render(<Popup />, mount);

export function destroy() {
  render(null, mount);
  host.remove();
}

What an iframe adds

An iframe is a separate document with its own CSS and global variables. If it’s on a different origin, the host gets very limited access to its Window and can’t read what’s inside. The two sides talk through postMessage, the browser API for sending messages between windows.

Here’s what Chromium returns when the page runs on port 8001 and the iframe comes from port 8002. A different port is already a different origin, so the page can’t read the iframe:

js
const frame = document.querySelector("iframe");
frame.contentDocument; // null
frame.contentWindow.document; // throws SecurityError

Stripe uses cross-origin iframes this way. Stripe.js, the script a shop adds to show Stripe’s payment form, loads its iframes from Stripe’s own origins, such as js.stripe.com. For Stripe’s embedded crypto purchase form, Stripe’s security guide says it directly: the form renders inside an iframe served from crypto.link.com. The shop’s own scripts can’t read what the buyer types there.

That separation costs you a few things:

  • The iframe is a rectangle. Nothing inside can draw outside it, so a chat button that opens into a panel has to ask the host page to resize the iframe.
  • The browser loads a second document.
  • The customer’s Content-Security-Policy can block your iframe through its frame-src list. That’s why Stripe’s guide lists its iframe origins for sites that set this header. On your side, frame-ancestors decides who may embed you, and leaving it out allows anyone.
  • Don’t expect its cookies or storage to follow a user between sites. Firefox keeps a separate copy for each site your iframe is embedded in, and other browsers restrict them too.
  • It needs a title, or screen reader users have to go inside to find out what it is.

Check both sides of every message. Send with an exact target origin instead of *, and on the receiving side verify the sender and the shape of the data:

ts
// On the host page
const WIDGET_ORIGIN = "https://widget.example.com";
const frame = document.querySelector<HTMLIFrameElement>("#widget")!;

window.addEventListener("message", (event) => {
  if (event.origin !== WIDGET_ORIGIN) return;
  if (event.source !== frame.contentWindow) return;
  if (event.data?.type !== "widget:height") return;
  if (!Number.isFinite(event.data.height)) return;

  frame.style.height = `${event.data.height}px`;
});

How I’d choose

What each option isolatesSwitch between them to see what stays out and what still gets through.

Shadow DOM

Same page, same JavaScript. The isolation is for styles.

  • Host CSS selectors stay out
  • Inherited styles still reach you
  • Host scripts can read your DOM
  • You can draw anywhere on the page

Cross-origin iframe

A separate document. The host can't look inside.

  • Host CSS stays out
  • Host scripts can't read your DOM
  • Limited to its own rectangle
  • Host and iframe talk through postMessage

For a popup, banner or chat button that sits on top of the page and doesn’t handle secrets, I’d start with Shadow DOM.

For a field the host must not read, such as a password, card number or token, I’d use an iframe served from your own origin. Shadow DOM doesn’t protect those from code running on the page.

You can combine them. Keep the popup itself in Shadow DOM and load an iframe only for the sensitive step.

If your embed renders HTML you don’t trust, use an iframe with sandbox. That attribute turns off scripts, forms and other features inside the iframe, and each allow-* value turns one of them back on. On same-origin content, don’t combine allow-scripts with allow-same-origin, because the document can then remove the sandbox.

If the untrusted part is text, such as an AI model’s reply, and you only need a few formats, you may not need an iframe. In the chat on my home page I don’t pass the reply to innerHTML. I build the DOM nodes myself, and I wrote up how that chat renders model output.

Whichever you pick, write down your embed’s boundaries early: what it can change on the page, what it owns and what it has to clean up when it closes. The destroy function above is the cleanup part, and I’d want it from the first version. If I worked on the Popupsmart runtime again, writing those boundaries down is what I’d do earlier.

References

  1. MDN: Using shadow DOM
  2. web.dev: Shadow DOM v1
  3. MDN: The iframe element
  4. MDN: Same-origin policy
  5. MDN: Window.postMessage()
  6. MDN: CSP frame-ancestors
  7. MDN: State partitioning
  8. Stripe: Integration security guide
  9. Gainsight Customer Communities: Widget rendering and DOM

Written by:

Full Stack Software EngineerSamsun, Türkiye

Full Stack Software Engineer. I started with client sites at an agency in 2019, then worked on embeds, a dashboard and analytics at a startup called Popupsmart.