Skip to content

Lesson 4 of 9 · 24m

Content Scripts, Isolated Worlds, and Safe DOM Integration

Content scripts are guests in hostile or fragile pages. Control injection timing, world boundaries, mutation behavior, and cleanup deliberately.

A content script is not your application running inside a friendly iframe. It is code inserted into someone else's runtime, beside unknown JavaScript, unpredictable CSP, infinite DOM mutation, and users who reasonably expect the page not to break. Treat it like integration engineering, not DOM scripting practice.

Static or programmatic injection — choose per feature

{
  "content_scripts": [{ "matches": ["https://app.example.com/*"], "js": ["content.js"], "css": ["content.css"], "run_at": "document_idle" }]
}

Static declarations are predictable and survive navigation without extra logic. Programmatic injection through chrome.scripting.executeScript is better when access is conditional on a click or optional permission:

await chrome.scripting.executeScript({ target: { tabId, frameIds: [0] }, files: ["content.js"] });

Prefer injecting a function with func and serializable args when the logic is small. For anything substantial, ship a bundled file so errors have stable filenames and source maps.

Isolated world means isolated, not irrelevant

By default content scripts run in an isolated JavaScript world: they see the same DOM but not the page's JavaScript variables. That protects both sides from accidental collisions, but it also means window.someAppObject is invisible. If you truly need main-world access, inject deliberately:

await chrome.scripting.executeScript({
  target: { tabId },
  world: "MAIN",
  func: () => window.dispatchEvent(new CustomEvent("audit-extension-probe"))
});

Main-world execution loses the isolation boundary. Never place secrets, privileged extension API handles, or unvalidated message bridges there.

DOM integration is a compatibility problem

Use a unique root element and namespace attributes:

const ROOT_ID = "bx-link-audit-root";
let root = document.getElementById(ROOT_ID);
if (!root) {
  root = document.createElement("div");
  root.id = ROOT_ID;
  root.dataset.bxAudit = "1";
  document.documentElement.append(root);
}

Make insertion idempotent because executeScript can run twice after retries or user clicks. Avoid broad selectors such as div or a on large pages; scope queries under the smallest stable container. If using Shadow DOM, remember it isolates style lookup but does not make hostile content unable to interact with your UI.

MutationObservers are budgets, not toys

Observe the narrowest node possible, batch callbacks, and disconnect when the feature is disabled. A naive observer on document.body with subtree: true can turn a chatty single-page app into a permanent CPU bill.

Field notes

  • document_start runs before most DOM exists; use it only when early interception is the actual requirement.
  • Pages can remove your nodes. Detect removal and re-insert carefully rather than fighting an adversarial loop.
  • Do not trust text, URLs, or data attributes read from the page; they are untrusted input.
  • Test inside iframes explicitly. all_frames changes both capability and risk, and frame IDs matter for targeted injection.

Was this lesson helpful?

Sign in to rate