An embedded component can hurt its host in three ways: its styles collide with the page's, its errors spread, or the page's Content-Security-Policy refuses it. Here is the defence for each one, and a test you can run in ten minutes.
When you put a widget on a page you do not own, three things can go wrong. The page's CSS and yours collide. An error in your code leaves a hole in somebody else's page. Or the page sends a Content-Security-Policy (CSP) that blocks what you load. Each one has a known defence: a Shadow DOM for the styles, an error boundary with fallback content for the errors, and a script that carries nothing inline for the CSP.
Most articles on this subject stop at the Shadow DOM. This one covers all three with plain browser code, then runs the test on a real page with Taggor, which gives every published component the three defences by default. It ends with what none of this protects against.
1. Styles collide: render inside a Shadow DOM
A widget that writes its markup straight into the page shares one style scope with it. The page says h2 { text-transform: uppercase } and your heading shouts. You say .card { padding: 0 } and the page's own cards collapse. Prefixing your classes does nothing against a theme that styles bare button and p with !important.
A shadow root is the browser's answer. Selectors do not cross it in either direction, so the page's rules do not reach your markup and yours do not reach the page. Two things do cross. Inherited properties such as color and font-family flow in from the page, so set your own on a wrapper inside the root. And the element that holds the root belongs to the page, so a page rule that matches your tag applies to it.
The other well-known answer is an iframe. It isolates more, because the widget becomes a separate document, and it costs more: the frame does not grow with its content or inherit the page's fonts. An earlier article compares the two.
2. An error spreads: catch it at the edge and keep a fallback
When an embedded script throws, the browser reports the exception to the page's own error handler, where a script from another origin often appears as the bare message "Script error." The page's other scripts go on running. The visitor sees your widget blank or half drawn, and the site owner gets an error in their monitoring that they did not write.
The defence has two halves: catch the failure at the edge of the widget, and have something to show in its place. The fallback to prefer is HTML the page's author wrote inside your tag, because it is already on the page and needs nothing from you:
const sheet = new CSSStyleSheet();
sheet.replaceSync(".card { padding: 1em; font: 16px/1.5 system-ui, sans-serif; } h2 { margin: 0; color: #0f766e; }");
class SignupCard extends HTMLElement {
connectedCallback() {
const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
root.adoptedStyleSheets = [sheet];
try {
root.replaceChildren(this.render());
} catch (error) {
console.error("signup-card failed", error);
root.replaceChildren(document.createElement("slot")); // show the page's own content
}
}
render() {
const card = document.createElement("section");
card.className = "card";
card.appendChild(document.createElement("h2")).textContent = this.getAttribute("headline") ?? "Join the list";
return card;
}
}
if (!customElements.get("signup-card")) customElements.define("signup-card", SignupCard);
The trick is in how custom elements treat their children. Until the element is defined, the children show like any other HTML. Once a shadow root is attached they are hidden, unless the root contains a <slot>. So one link inside the tag covers three cases: the script has not loaded, the script was blocked and never will, or the component threw and put the slot back.
3. The CSP says no: carry nothing inline
A strict policy refuses inline scripts, inline styles and eval, so a widget that injects a <style> tag or builds code from strings arrives unstyled, or does not arrive. The rules for the author are short. Ship one external script, which the page allows by origin and by nonce. Apply styles as constructed style sheets through adoptedStyleSheets, as the code above does, in place of a style tag. Never use eval or new Function, and build the DOM with nodes, not HTML strings, so that a page that requires Trusted Types accepts you.
We ran the element above in Chromium under default-src 'none'; script-src 'nonce-…'; style-src 'nonce-…'; require-trusted-types-for 'script', and it rendered with its styles. Taggor's runtime works the same way, and its docs give the exact policy a site needs: the nonce on the snippet, the CDN origin in script-src, and the Trusted Types policy named taggor. If the policy does not allow the script, the browser refuses it, the tag is never activated, and the fallback inside it stays on the page.
The test: a page that is hostile on purpose
Here is the part you can run. taggor dev previews a component, mounted by the same runtime a site gets, on a test page whose global CSS is written to do damage: * { all: unset; }, forced borders and padding on every p, div and [class], and a 40-pixel red-on-yellow rule for every button. A second script fills window.React, window.Preact, window.$, window.h and window._ with junk, in case the component leans on a global.
One note on the pictures before the commands. They draw signup-inline as the finished form from Taggor's own showcase: an email field and a button in one pill. init does not create that form. It creates a starter with the same tag, a card with a single prop, headline, in components/signup-inline/src/index.tsx, and that file is where a form of your own goes. The steps below use the starter, so the component on your screen is a teal heading, and every result described here is the starter's.
npx taggor login
npx taggor init --component signup-inline
cd <the folder init printed>
npm install
npx taggor dev
Open the address dev prints (http://127.0.0.1:4321/ by default; if it says the port is already in use, pick another with --port <n>). The starter shows a teal heading, as its own CSS says. Below it, click "Show what this page's global CSS does to ordinary elements" to open that section: it has a heading, a paragraph and a button of the same page that are not in a shadow root.
Now make the component fail. In components/signup-inline/src/index.tsx, replace render with a version that throws on two magic values:
render: (props, { part }) => {
if (props.headline === "boom") throw new Error("boom");
if (props.headline === "late") setTimeout(() => { throw new Error("late"); }, 0);
return (
<section class="card" part={part("card")}>
<h2>{props.headline}</h2>
</section>
);
},
Then give it a page with something to lose. Save this as host.html in the folder init created, the one you ran dev from, next to its taggor.json:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Host page</title>
<style>
body { font: 18px/1.5 Georgia, serif; margin: 40px; }
h2 { color: crimson; text-transform: uppercase; letter-spacing: 4px; }
.card { border: 6px dashed crimson; padding: 40px; }
</style>
</head>
<body>
<h2>A heading of the page</h2>
<div class="card">A card of the page</div>
<signup-inline headline="Join the list">
<a href="mailto:hello@example.com">Write to us to join the list</a>
</signup-inline>
<p><button type="button" id="count">Clicked 0 times</button></p>
<p id="errors">Errors that reached the page: 0</p>
<script>
let clicks = 0;
let errors = 0;
document.getElementById("count").addEventListener("click", (event) => {
clicks += 1;
event.target.textContent = `Clicked ${clicks} times`;
});
window.addEventListener("error", () => {
errors += 1;
document.getElementById("errors").textContent = `Errors that reached the page: ${errors}`;
});
</script>
</body>
</html>
Stop taggor dev with Ctrl+C and start it on that page:
npx taggor dev --host-html host.html
The page and the component both have an h2 and a .card, and neither one touches the other. Type boom into the headline field of the Playground panel. The component is gone and the link you wrote inside the tag is in its place. The console has one error, [taggor] signup-inline: component failed (render) Error: boom followed by its stack trace, the button goes on counting, and the page's error count is 0. A component that failed stays on its fallback, and changing the prop back does not retry it, so it cannot fail in a loop. Reload the page to mount it again.
Reload the page, then type late. The heading shows "late", and this time the page's error count goes to 1. That is the honest edge of an error boundary, ours and anyone's: it catches what throws while the component renders or in one of its event handlers, and it cannot catch a timer callback that throws later. Remove the two throw lines when you are done.
On a published site the same rules hold, plus one. If the Taggor script never arrives (an ad blocker, the page's CSP, the CDN unreachable), the tag is never activated, and the docs say what the visitor sees: all the HTML inside it, visible and working.
What this does not protect against
A Shadow DOM is a style boundary, not a security boundary. Taggor's shadow roots are open, so a script of the page can reach in through element.shadowRoot. And embedded code runs with the page's own privileges: it can read the page's DOM like any other script there. If the code comes from someone you do not trust, put it in a sandboxed iframe on another origin. Taggor is for components that you or your coding agent wrote; the automated checks on every publish reduce risk, and they are not a security audit.
There are smaller limits too. Errors thrown outside rendering and event handlers (a timer, a promise nobody catches) reach the page's handler, as the late test showed. Custom element names are global to a page: if another script has already defined your tag, Taggor does not overwrite it, and the component is not mounted. And in a browser without Custom Elements, Shadow DOM or ES modules the loader does nothing, and the fallback is what shows.
The short version
Render in a shadow root, catch failures at the widget's edge, let the page's own HTML be the fallback, and carry nothing inline. You can do all of it by hand, starting from the element above.
Taggor does it for every component you publish, and adds the parts around it: one async snippet per site whose only global is window.taggor, versions with a rollback, and the hostile test page before anything goes out. The CLI quickstart goes from signing in to a component on a page of your own. If you run the test and something leaks that we did not list, tell us in the comments: that is a bug report we want.



Top comments (0)