Extension Sandbox iframe, Content Security Policy, and postMessage Security
How sandboxed extension pages relax CSP for eval, block remotely hosted code in privileged contexts, and use postMessage safely.
This page summarizes Chrome extension documentation on Manifest V3 security: strict Content Security Policy on extension pages, the ban on remotely hosted code, and sandboxed extension pages loaded in an iframe where inline script and eval() are allowed because those pages have no access to extension APIs. It also ties in the HTML specification’s rules for cross-document messaging and Chrome’s guidance on comparing web origins when handling postMessage events.
Manifest V3 remotely hosted code: why logic must stay in the package
Section titled “Manifest V3 remotely hosted code: why logic must stay in the package”Under Manifest V3, an extension may only run JavaScript (and WebAssembly) that ships inside the extension package and is subject to store review. Remotely hosted code (RHC) means anything the browser executes that was loaded from outside the package—not data such as JSON or CSS.
Remotely hosted code, or RHC, is what the Chrome Web Store calls anything that is executed by the browser that is loaded from someplace other than the extension’s own files. Things like JavaScript and WASM. It does not include data or things like JSON or CSS.
— Chrome, Deal with remote hosted code violations
Program policies require that the full functionality of an extension be discernible from submitted code. Common rejections (notification Blue Argon) include a <script> tag pointing off-package, eval() on strings fetched remotely, or an interpreter that runs remote command data as logic. Allowed exceptions are narrow: documented APIs such as the Debugger API and User Scripts API, and code in contexts isolated from extension APIs (including sandboxed pages and certain iframes)—still subject to privacy and review expectations.
Fetching remote data without executing it remains possible—for example syncing account data, A/B configuration where logic stays packaged, images, or server-side crypto—see Additional Requirements for Manifest V3 and Improve extension security.
Extension sandbox manifest pages: unique origin without extension APIs
Section titled “Extension sandbox manifest pages: unique origin without extension APIs”The sandbox manifest key lists HTML pages served in a sandboxed unique origin. Two consequences define the pattern:
A sandboxed page won’t have access to extension APIs, or direct access to non-sandboxed pages (it may communicate with them using postMessage()).
— Chrome, Manifest - Sandbox
A sandboxed page is not subject to the Content Security Policy (CSP) used by the rest of the extension (it has its own separate CSP value). This means that, for example, it can use inline script and eval().
— Chrome, Manifest - Sandbox
List only top-level pages you load in windows or frames; scripts and styles pulled into those pages inherit the embedding frame’s sandbox. Custom sandbox CSP must include the sandbox directive and must not include allow-same-origin (Manifest - Sandbox). From Chrome 57 onward, sandboxed extension pages cannot embed external web content in frames; legacy Chrome Apps documented the same constraint.
Why sandbox instead of relaxing extension CSP
Section titled “Why sandbox instead of relaxing extension CSP”Extension pages enforce a strict minimum CSP: you cannot add 'unsafe-eval' to extension_pages—Chrome throws at install time (Manifest - Content Security Policy).
eval is dangerous inside an extension because the code it executes has access to everything in the extension’s high-permission environment.
— Chrome, Use eval() in sandboxed iframes
The recommended pattern: keep privileged UI and service worker code CSP-clean; load sandbox.html in a hidden iframe; exchange serializable data only via postMessage(). Improve extension security notes that remotely hosted code may run inside a sandboxed iframe when it does not need the embedding page’s DOM—still a review-sensitive area; packaged sandbox pages are the primary documented path for templating libraries that need new Function().
postMessage(): wiring sandboxed code to extension pages
Section titled “postMessage(): wiring sandboxed code to extension pages”Cross-document messaging is the bridge between sandboxed and privileged contexts. The HTML specification’s introduction shows the usual pattern: the parent calls postMessage on the child contentWindow, and the child registers addEventListener('message', …) and checks event.origin before acting.
For extensions, the parent is typically an extension page or service worker opener; the child is sandbox.html. Data must be structured-cloneable (no functions)—see the notes in Use eval() in sandboxed iframes.
postMessage() sender rules: targetOrigin and confidential data
Section titled “postMessage() sender rules: targetOrigin and confidential data”Authors should not use the wildcard keyword (*) in the targetOrigin argument in messages that contain any confidential information, as otherwise there is no way to guarantee that the message is only delivered to the recipient to which it was intended.
— WHATWG, Cross-document messaging — Edition for Web Developers
Chrome’s Web Security guidance matches this: specify an exact target origin when sending sensitive payloads; on receive, validate event.origin (prefer the Origin API over naive string tricks).
postMessage() receiver rules: origin, payload shape, and denial of service
Section titled “postMessage() receiver rules: origin, payload shape, and denial of service”Authors should check the origin attribute to ensure that messages are only accepted from domains that they expect to receive messages from.
— WHATWG, Cross-document messaging
After origin checks, validate message shape—compromised senders or XSS on the sender side can propagate attacks if the receiver trusts raw event.data. Rate-limit handlers when accepting messages from broad sources; high-volume message events can amplify into denial-of-service (Cross-document messaging).
Legacy Chrome Apps often used postMessage(..., '*') toward a sandboxed iframe because the app could not read the sandbox’s opaque origin string; contained app boundaries reduced risk, but web extensions should prefer explicit origins or pinning (below).
Opaque origins: why event.origin === "null" is not enough
Section titled “Opaque origins: why event.origin === "null" is not enough”Sandboxed iframes (<iframe sandbox="allow-scripts">) and sandboxed extension pages use opaque origins whose serialization is the string "null". Two unrelated sandboxes both report "null", so string equality does not identify the sender.
Chrome’s Compare and validate web origins and sites recommends Origin.from(event) on browser-dispatched MessageEvents, or pinning the opaque origin on first message from event.source === expectedWidgetWindow, or using a dedicated MessageChannel transferred at initialization. Do not validate with startsWith, includes, or hostname splitting.
| Check | Safe approach | Risky approach |
|---|---|---|
Tuple origin (e.g. https://app.example.com) |
Origin.from(event).isSameOrigin(Origin.from(TRUSTED)) |
event.origin.includes('example.com') |
| Sandbox iframe inside extension | Pin opaque origin or verify event.source |
Accept any event.origin === 'null' |
Redirect / returnTo URLs |
isSameSite() with Public Suffix List |
Manual subdomain string rules |
The origin model for storage and messaging assumes TLS for trustworthy domain binding; DNS spoofing is mitigated by HTTPS and certificate validation, not by storage APIs alone.
Content Security Policy: extension_pages versus sandbox
Section titled “Content Security Policy: extension_pages versus sandbox”Manifest V3 splits CSP in content_security_policy:
| Context | Default (if unset) | Minimum on extension pages |
|---|---|---|
extension_pages |
script-src 'self'; object-src 'self'; |
script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; — no 'unsafe-eval' (Manifest - Content Security Policy) |
sandbox |
sandbox allow-scripts allow-forms allow-popups allow-modals; script-src 'self' 'unsafe-inline' 'unsafe-eval'; child-src 'self'; |
Customizable, but must stay within sandbox rules (Manifest - Sandbox) |
Content scripts in the isolated world get their own CSP (no eval, no remote scripts). Scripts injected into the main world follow the page’s CSP. Sensitive work—privileged fetches, secrets, broad extension APIs—belongs in the service worker, not in content scripts (Stay secure, Message passing).
Privileged extension code: messaging, XSS, and fetch proxies
Section titled “Privileged extension code: messaging, XSS, and fetch proxies”Even with a sandbox, the receiver of sandbox output must treat HTML and JSON like untrusted input unless it was generated under your control. Prefer JSON.parse, textContent / innerText, and function forms of setTimeout over eval, innerHTML, and string setTimeout (Content scripts — Stay secure, Cross-origin network requests).
Do not let content scripts choose arbitrary URLs for background fetch—a malicious page can forge runtime.sendMessage and exfiltrate cross-origin data. Pass identifiers only and build URLs in the service worker (Cross-origin network requests).
Cloudflare Agents use a related pattern for untrusted generated code: a hidden iframe with sandbox="allow-scripts", code delivered via postMessage, and a tight default CSP on the iframe document—relaxing connect-src can leak tool output to external systems.
Common mistakes when using sandbox iframes and postMessage
Section titled “Common mistakes when using sandbox iframes and postMessage”- Shipping remote
<script src="https://…">on extension pages or executing fetched JS strings outside approved APIs (Troubleshooting Chrome Web Store violations). - Adding
'unsafe-eval'tocontent_security_policy.extension_pagesinstead of usingsandbox.pages(Manifest - Content Security Policy). - Forgetting to list
sandbox.htmlundersandbox.pages, so the page runs with full extension privileges (Use eval() in sandboxed iframes). - Using
postMessage(data, '*')for secrets or trusting rendered sandbox HTML in privilegedinnerHTMLwithout remembering the sandbox is low-privilege, not automatically trustworthy content (Use eval() in sandboxed iframes). - Letting content scripts trigger open-ended network or tab APIs (Stay secure).
How to check this on your site
Section titled “How to check this on your site”-
Open
manifest.jsonand confirmmanifest_versionis 3,sandbox.pageslists every sandbox HTML entry point, andcontent_security_policy.extension_pagesdoes not include'unsafe-eval'or remote hosts—see Manifest - Content Security Policy and Manifest - Sandbox. -
Search the extension package for
http://,https://in<script src, dynamicimport(),eval(,new Function(, and CDN URLs; compare findings with Deal with remote hosted code violations and Troubleshooting Chrome Web Store violations. -
Exercise the sandbox
iframeflow in DevTools: verify privileged listeners reject unexpectedevent.origin/event.source, and that sandboxed code cannot callchrome.*orbrowser.*APIs (Manifest - Sandbox). -
On the Chrome Web Store dashboard, set Remote Code declarations accurately if any exempt remote execution applies (Fill out the privacy fields).
-
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about, and we will fix or clarify it.