Your company sells a customer-support chat and help-center widget. Customers embed it on their websites with a snippet. It is installed on 40,000 sites with a combined 500 million page views per month, ranging from small WordPress blogs to large e-commerce sites with strict Content Security Policies.
The widget shows a launcher button, opens a chat panel, can show help articles, and offers a JavaScript API so the host site can identify the logged-in user, open the widget programmatically, and listen to events (for example, "conversation started").
Design the embeddable widget SDK: the snippet and loader, how the widget is isolated from the host page (and the host from the widget), the host-facing API, versioning and rollout across 40,000 sites you do not control, security (including identity verification), privacy and cookie restrictions, performance budgets, and how your team supports and evolves it.
A third-party widget is the most hostile environment front-end code can run in. You do not control the page, its CSS, its JavaScript globals, its CSP, its framework, its polyfills or its release schedule, and the page owner does not control you either. Every byte you ship is paid for by someone else's Core Web Vitals, and every bug you ship appears on 40,000 sites at once.
The design priorities, in order:
Array.prototype.find patched by an old library),
CSP restrictions, aggressive privacy settings.boot, identify, open, close, on(event), update(attributes), shutdown (logout).shop.example.com to help.example.com)?window.AcmeChat that queues calls made before the
loader arrives, then injects the loader <script async>.https://widget.acmechat.com/frame?v=... that runs the full chat app with its own framework, styles and network
connections.| Isolation option | Pros | Cons |
|---|---|---|
| Inline DOM, no isolation | Simplest; full access to the page | Host CSS breaks you; your CSS breaks the host; shares globals; any XSS in your code is XSS on the host |
| Shadow DOM | Style encapsulation both ways; light; can overlay page naturally | Same JS realm (globals, prototypes can be tampered with); inherited properties (font, colour) still leak in unless reset; host scripts can reach into an open shadow root |
| Iframe on your own origin | Strong isolation: separate realm, CSS, storage, CSP, crashes; host cannot read conversation data | Sizing and positioning need a bridge; focus management across frames; one more document to load; third-party storage restrictions |
The launcher is small and must feel native, so Shadow DOM (with all: initial resets) is enough. The chat panel
handles user data and runs a full app, so it lives in an iframe on our origin: the host page cannot read messages, and
a compromise of the host does not expose other users' conversations.
<script>
(function (w, d, id) {
if (w.AcmeChat) return;
var q = [];
var stub = function () { q.push(arguments); };
stub.q = q;
w.AcmeChat = stub;
var s = d.createElement('script');
s.async = true;
s.src = 'https://cdn.acmechat.com/loader/v1/loader.js';
s.dataset.siteId = id;
d.head.appendChild(s);
})(window, document, 'site_123');
AcmeChat('boot', { language: 'en' });
</script>
The URL contains a major version (v1), never a full version. Strict-CSP sites can use an external file version
of the snippet with a nonce, documented separately.
{
"siteId": "site_123",
"enabled": true,
"widgetVersion": "1.42.3",
"frameUrl": "https://widget.acmechat.com/frame/1.42.3/index.html",
"theme": { "primary": "#5b3cc4", "position": "bottom-right", "offset": { "x": 20, "y": 20 } },
"features": { "helpCenter": true, "fileUpload": false },
"pageRules": [{ "match": "/checkout*", "show": false }],
"identityVerification": "required",
"allowedOrigins": ["https://shop.example.com", "https://help.example.com"]
}
widgetVersion per site is how we run staged rollouts: the loader is stable and tiny, the heavy app version is
chosen per site by config.
type HostToFrame =
| { ns: 'acme'; v: 1; type: 'boot'; payload: BootOptions }
| { ns: 'acme'; v: 1; type: 'identify'; payload: { userId: string; userHash: string; traits?: Traits } }
| { ns: 'acme'; v: 1; type: 'open' | 'close' | 'shutdown' };
type FrameToHost =
| { ns: 'acme'; v: 1; type: 'ready' }
| { ns: 'acme'; v: 1; type: 'resize'; payload: { width: number; height: number; mode: 'panel' | 'fullscreen' } }
| { ns: 'acme'; v: 1; type: 'event'; payload: { name: 'conversation_started' | 'message_received' | 'closed'; data?: unknown } }
| { ns: 'acme'; v: 1; type: 'unread'; payload: { count: number } };
Rules: always pass an explicit targetOrigin (never "*") when posting into the frame; in the frame, accept
messages only from event.source === window.parent and from an origin in the site's allowedOrigins; in the loader,
accept messages only from our frame's origin and contentWindow. Messages are namespaced and versioned; unknown types
are ignored, which keeps old loaders and new frames compatible.
interface AcmeChatApi {
(cmd: 'boot', options: BootOptions): void;
(cmd: 'identify', user: { userId: string; userHash: string; email?: string; name?: string }): void;
(cmd: 'update', attributes: Record<string, string | number | boolean>): void;
(cmd: 'open' | 'close' | 'toggle'): void;
(cmd: 'on', event: WidgetEventName, handler: (data: unknown) => void): void;
(cmd: 'off', event: WidgetEventName, handler: (data: unknown) => void): void;
(cmd: 'shutdown'): void; // logout: clears identity and conversation state on this device
}
interface BootOptions {
language?: string;
hideLauncher?: boolean; // host provides its own button
container?: HTMLElement; // inline mode instead of floating
zIndex?: number;
}
A command-style function API (rather than an object with methods) matches the snippet stub, so calls work before and
after load, and adding commands never breaks old snippets. An npm package (@acmechat/widget) offers the same API
with types and React bindings for SPA customers, but still loads the runtime from the CDN so all sites get fixes.
identify without verification lets anyone open devtools and claim to be another user. The customer's server
computes userHash = HMAC-SHA256(secret, userId) (or issues a short-lived signed JWT), and our API rejects
identification without a valid hash. The secret never touches the browser.
?acmechat_debug=1 logs lifecycle and bridge messages to the console, and support can request
a diagnostic bundle.script-src https://cdn.acmechat.com, frame-src https://widget.acmechat.com,
connect-src for the API and WebSocket, img-src for avatars).window.onerror.const _fetch = window.fetch.bind(window)) and avoid relying on
prototypes that old libraries patch. Inside the iframe this problem disappears, which is another reason to keep logic
there.window.AcmeChat. No polyfills that modify globals; bundle ponyfills instead.:host { all: initial; }) plus explicit font and colour, since inherited properties cross
the shadow boundary.nomodule only if your customer base needs it), and defer non-essential work to requestIdleCallback./v2/); v1 remains supported for years, typically as a
compatibility shim over the v2 internals. Deprecations are announced in the dashboard and through console warnings in
debug mode only.integrity
hash for customers whose security policy requires it, accepting they will update manually.Inside a third-party iframe, storage is partitioned by top-level site in Chrome, Firefox and Safari, and Safari blocks third-party cookies entirely; Chrome also restricts them for some users. Consequences:
Partitioned
attribute) for HTTP-only session cookies.shop. and help. of the same site) works because partitioning is by site
(scheme + registrable domain), not by origin.identify with a verified user, not cookies.boot({ consent: false }) or a CMP integration delays non-essential storage and analytics.X-Frame-Options/frame-ancestors on the widget frame restricted to the site's allowedOrigins, preventing other
sites from framing a customer's widget to phish.The launcher is a real <button> with an accessible name and unread count announced via aria-live. Opening the
panel moves focus into the iframe and traps it in modal mode; closing returns focus to the launcher. Escape closes.
Respect prefers-reduced-motion and the host's zoom levels. Test with screen readers on top of busy host pages.
Customers are choosing between you and Intercom, Zendesk or Crisp, so the widget is the product: build it. What you can buy is infrastructure: multi-CDN delivery, a realtime service (Ably, Pusher, or managed WebSocket gateways) if you do not want to run your own, and error monitoring for the widget itself (with strict scrubbing).
Why not render everything in Shadow DOM and skip the iframe? Shadow DOM isolates styles, not JavaScript or data. Host scripts (or an XSS on the host) could read conversations and tokens. The iframe gives a separate origin, realm and storage, which is what user data needs.
How does the iframe resize?
The frame posts resize messages with desired dimensions and mode; the loader updates the container with CSS
transitions, and on small screens switches to fullscreen. The loader enforces limits so a buggy frame cannot cover the
whole page unexpectedly.
A customer's SPA calls boot on every route change.
Make commands idempotent: boot with the same options is a no-op, and route changes are detected via the History API
and popstate so page rules re-evaluate without re-booting.
How do you test across thousands of different host sites?
A test harness of hostile pages (global CSS resets, * { box-sizing: content-box }, patched prototypes, strict CSP,
huge z-index overlays), plus synthetic monitoring on a sample of real customer sites, plus RUM error rates by site.
How would you handle a bad release that breaks a large customer's checkout? Immediate per-site rollback via config (the loader picks up the previous version within the config TTL), global rollback if widespread, then a post-incident review on why staged rollout did not catch it.
Spotted a mistake or a rights concern? Report an issue