IHOR.DEVKNOWLEDGE_BASE
MENU

~/blog / Security / content-script-isolation-and-page-security.md

// guide · 4 min read

Content Script Isolation and Page Security

Understand isolated-world JavaScript, shared DOM, page-main-world bridges, untrusted page data, and lifecycle cleanup for Chrome content-script interfaces.

Quick answer

The default isolated world separates a content script's JavaScript variables from the page's variables. It does not give the extension a private DOM. Both can observe and modify page elements, attributes, and event-visible data. Treat everything read from the document as untrusted, and keep privileged extension operations behind a narrow worker message contract.

Use the isolated world unless a feature truly needs page JavaScript state. A main-world bridge can expose selected information, but it executes alongside page code and should carry no secrets or privileged logic. A message arriving through that bridge is still page-originated input, not authenticated extension data.

Practical implementation steps

Identify what must be read

Computed styles and selected DOM elements often need no main-world execution. Font Picker's public description includes CSS properties and visible text styles, which illustrates this kind of document-facing job. It does not expose its execution-world implementation. Ask whether a proposed bridge accesses a real page variable or merely compensates for an unclear DOM query.

Keep injected UI out of trust decisions

Use scoped styles or a shadow root to reduce CSS collisions, but do not treat them as a confidentiality barrier. The host page remains an adversarial environment. Never place tokens in DOM attributes or trust a click merely because its target resembles your button. Have the privileged context verify the requested operation and its allowed target independently.

Bound page input

Limit text lengths, element traversal, and work triggered by page changes. A page can create a very large DOM or repeatedly mutate it. Batch mutation work rather than rescanning the whole document for every record. Validate URLs using parsed URL components and an explicit scheme policy. Send only required fields to the worker; do not forward arbitrary page objects or entire HTML documents.

Handle reinjection and cleanup

A user can invoke a tool repeatedly on a single-page application. Prevent duplicate listeners and overlays, track the current target, and provide teardown for observers and UI. A pathname change may not create a new document, while a full navigation destroys the old execution context. Test both flows instead of assuming every route change resets the content script.

Implementation example

This content-script fragment displays a bounded selection as text in an overlay. It does not expose extension secrets or call privileged APIs. A production overlay still needs accessible interaction, styling, duplicate-injection handling, and cleanup.

const selected = window.getSelection()?.toString().slice(0, 500) ?? "";
const panel = document.createElement("aside");
panel.setAttribute("aria-label", "Selection preview");
const content = document.createElement("p");
content.textContent = selected || "No text selected";
panel.append(content);
document.documentElement.append(panel);

function cleanup() {
  panel.remove();
}

textContent prevents interpreting the selection as markup. It does not prove the selected text is correct, harmless, or permitted to send elsewhere. Keep display safety, data accuracy, and privacy as separate checks. If a bridge uses postMessage, validate source, origin, message type, and schema; same-page scripts can still imitate that message format.

Tradeoffs and alternatives

An isolated content script offers extension-managed code and access to a limited set of extension APIs, while main-world code can interact with page variables at a cost in trust. A bridge should expose only the minimum data needed by the feature. Use the normal DOM when it supplies the answer; avoid a general-purpose command channel between the page and worker.

Common mistakes

  • Calling isolated world a private page or private DOM.
  • Assuming a shadow root hides secrets from the host.
  • Forwarding page-supplied commands to browser APIs.
  • Rescanning unbounded documents on every mutation.
  • Leaving duplicate listeners after repeated invocation.

Production checklist

  • Execution world follows a specific data need.
  • Page input is bounded and validated.
  • UI styling is separate from security assumptions.
  • Privileged requests have independent checks.
  • SPA changes and full navigation are tested.
  • Reinjection and teardown are implemented.

FAQ

Can page code read content-script variables?

Not directly across the isolated JavaScript world. Data deliberately written into the shared DOM or passed through a bridge becomes observable through those channels.

Does checking event.source authenticate a page bridge?

It helps reject other windows, but code in the same page can still send messages. Treat accepted messages as untrusted page input and authorize only narrow operations.

Conclusion

Use isolation for JavaScript separation, validation for page input, and authorization for privileged work. Those boundaries complement one another. Keep bridges narrow and avoid mistaking a styling or execution-world feature for a complete security boundary.

Primary sources

Ihor Kharchyshyn

Independent full-stack product engineer writing source-backed implementation guides for browser extensions and modern web products.

Need this implemented in a real product?

Browser tools with a clear purpose, focused permissions, and a maintainable Manifest V3 architecture.