iFrame Security
An iframe puts one web page inside another. That makes it useful for maps, videos, payment forms, and widgets, and it also makes it one of the riskiest elements in HTML, because two parties now share one screen.
Iframe security has two sides. In one, you embed someone else's page and must limit what it can do to your visitors. In the other, someone else embeds your page, usually to trick your visitors. This lesson covers both. The element itself is introduced in the earlier iFrame lesson, and the wider topic of third-party code in Third-Party Content Security. Here we go deeper on the threats.
What You Will Learnβ
- The two directions of iframe risk
- What an embedded page can do to yours and to your visitors
- How to harden an embed: trust,
sandbox,allow,referrerpolicy, andframe-src - What clickjacking is, and how
frame-ancestorsstops it - How to use
postMessagesafely - Why a visitor-supplied iframe address is dangerous
- How to check a page's embeds
The Big Ideaβ
A frame is a window into someone else's page. Treat it like a guest: decide who may come in, what they may touch, and make sure no one can use your own page as a disguise.
- A Hardened Embed
- Clickjacking Lab
- postMessage Lab
- Embed Checker
<iframe
src="https://widgets.example.net/map"
title="Map to the bakery"
sandbox="allow-scripts"
allow=""
referrerpolicy="strict-origin-when-cross-origin"
loading="lazy"
width="600" height="400"></iframe>
Content-Security-Policy: frame-src https://widgets.example.net; frame-ancestors 'self'
This is a picture of the idea, drawn with ordinary boxes. No real frame is loaded. In a real attack, the attacker's page places your page, made see-through, on top of a decoy so that clicks land on your page's buttons.
Your page embeds a widget from https://widgets.example.net and listens for its messages. Pick how your message handler decides who to trust.
if (event.origin.startsWith("https://widgets.example.net")) handle(event.data);| Message from | Handled? | Correct? |
|---|---|---|
https://widgets.example.netThe real widget | Accepted | Right |
https://widgets.example.net.attacker.exampleA look-alike host that starts with the same text | Accepted | Wrong |
https://notwidgets.example.netA different host that contains the same text | Ignored | Right |
http://widgets.example.netThe real host, but over http | Ignored | Right |
https://attacker.exampleAn unrelated page | Ignored | Right |
1 message(s) were handled or ignored wrongly.
An origin is the scheme, host, and port. Compare it as a whole, with strict equality, or against a list of exact origins. Partial text checks are easy to fool with look-alike host names.
Loading the checker...
Two Directions of Riskβ
| Direction | The question | Main risks | Main defences |
|---|---|---|---|
| You embed them | What can the embedded page do to my visitors and my page? | Misleading content, popups, redirects, tracking, misuse of powerful features, a compromised provider | Trust the source, sandbox, allow, referrerpolicy, CSP frame-src, click to load |
| They embed you | Can someone use my page inside their page against my visitors? | Clickjacking, where a visitor is tricked into clicking your buttons | CSP frame-ancestors, X-Frame-Options |
When You Embed Someone Elseβ
A frame from another origin is separated from your page by the same-origin policy (see HTML Security Basics), so it cannot read your page's content. But it still has plenty of power inside its own rectangle, and some outside it:
- It can show anything, including a fake login form designed to fool your visitors.
- It can run its own scripts, load its own resources, and track visitors with its own cookies.
- It can try to navigate the whole page somewhere else, or open popups and new windows. Browsers restrict some of this, but not all, and not in all cases.
- It can ask for powerful features, such as the camera, microphone, location, or fullscreen, if you let it.
- It can turn bad overnight. If the provider is hacked or sold, every site that embeds it inherits the change.
Harden it, step by stepβ
- Choose the source carefully. Embed only from providers you trust. Prefer ones with a good record and clear privacy terms.
- Never let a visitor choose the address. If your page builds an
iframefrom visitor input, an attacker can point it anywhere. Allow only a short list of exact hosts, and check the scheme. - Add
sandbox. An emptysandboxremoves almost every power. Then add back only what the embed needs, as covered in Sandbox Attribute. - Control
allow. Features such as the camera need explicit permission throughallow. Grant none by default, and name only what is needed, such asallow="fullscreen". - Set
referrerpolicy. This controls how much of your page's address is sent to the embedded host.strict-origin-when-cross-originis a common, sensible choice. See noreferrer. - Restrict what you can embed with CSP. The
frame-srcdirective of a Content Security Policy lists the hosts your page may frame, so a mistake or injected code cannot add a frame from elsewhere. See Content Security Policy. - Use
httpsonly. Anhttpframe on anhttpspage is mixed content, and is blocked or upgraded by browsers. - Give it a
title, so screen reader users know what the frame is. - Load it only when needed. Use
loading="lazy", or a click-to-load button, so no third party is contacted until the visitor chooses. See Lazy Loading.
The Embed Checker tab above reviews a few of these automatically. Load the messy embeds and fix the findings.
When Someone Embeds You: Clickjackingβ
In clickjacking, an attacker builds a page and loads your page in a hidden, see-through frame on top of a harmless-looking decoy. The visitor thinks they are clicking "Claim your prize", but the click lands on your page's button underneath, such as "Delete account", "Transfer", or "Like".
Open the Clickjacking Lab. Drag the slider to reveal the hidden frame, then tick the checkbox that represents the defence, and click the prize button.
The defence is to tell the browser that your pages must not be shown in someone else's frame.
frame-ancestorsβ
The modern way is the frame-ancestors directive of a Content Security Policy, sent as an HTTP response header:
Content-Security-Policy: frame-ancestors 'none'
| Value | Who may frame the page |
|---|---|
'none' | Nobody |
'self' | Only your own origin |
https://partner.example.com | Only that origin |
frame-ancestors only works as an HTTP header. It is ignored in a CSP that is set with a meta tag in the HTML. If you cannot set headers, check your hosting platform for a way to add them.
X-Frame-Optionsβ
The older header X-Frame-Options has two useful values: DENY (nobody) and SAMEORIGIN (only your own origin). Many sites send both for older browsers. If both are present, current browsers follow the CSP frame-ancestors.
Why "frame-busting" scripts are not enoughβ
Old advice was to add a script that checks whether the page is inside a frame and breaks out. This is unreliable, because a framing page can interfere with it (for example, by sandboxing the frame). Use the headers, and treat any script as an extra, not the defence.
More protection for sensitive actionsβ
For actions that matter, such as deleting an account or moving money, do not rely on a single click. Ask for confirmation, re-enter a password, or use a one-time code. Cookies with a SameSite setting also reduce what a framed page can do on a visitor's behalf, and are set by the server.
Talking to a Frame Safely: postMessageβ
Frames and their parent pages can send each other messages with postMessage. It is useful, and a common source of bugs, because any page can send a message to any window it can reach. Your handler must decide who to believe.
window.addEventListener("message", function (event) {
if (event.origin !== "https://widgets.example.net") return;
// Treat event.data as untrusted input, even from the right origin
if (typeof event.data !== "object" || event.data === null) return;
if (event.data.type === "resize" && Number.isFinite(event.data.height)) {
frame.height = Math.min(Math.max(event.data.height, 100), 2000);
}
});
Rules to follow:
- Check
event.originagainst an exact value, or a list of exact values. Use strict equality, notstartsWithorincludes, which look-alike host names can fool. Try it in the postMessage Lab. - Check the shape of
event.data, and never use it withinnerHTML,eval, or as a URL without checking. It is untrusted input. - When sending, give a specific
targetOrigin, such as"https://widgets.example.net", and avoid"*"for anything sensitive. With"*", the message goes to whatever page happens to be in that window. - Check
event.sourceif you have more than one frame, so you know which one sent it.
Frames From Visitors, and srcdocβ
If your site lets visitors add content, think carefully about frames:
- Never allow raw
iframetags in comments or profiles. Strip or escape them (see XSS Basics). - If you offer an "embed a video" feature, accept a video identifier or a link from a short allow-list of sites, and build the
iframeaddress yourself from that. srcdocputs HTML directly in the attribute. If visitor text gets intosrcdoc, it is XSS inside a frame. Escape it, and combine withsandbox.- Do not allow
javascript:ordata:addresses as a frame source. Check the scheme againsthttpsonly.
When a Site Refuses to Be Framedβ
Many sites send frame-ancestors or X-Frame-Options so they cannot be embedded, which is a good thing. If you try to embed one, the frame shows an error, and the console says it refused to display the page. Do not look for a way around it. That setting is a security choice by the owner. Link to the page instead, or use the provider's official embed option if they offer one.
Checking Your Setupβ
- Open DevTools, then Console, and reload. Look for messages about frames that were refused or blocked.
- Open Network, click your page's request, and read the Response Headers. Is
frame-ancestorsorX-Frame-Optionspresent? - Open Elements, and check each
iframeforsandbox,allow,title, andreferrerpolicy. - From the command line,
curl -I https://your-site.exampleshows a page's headers without downloading it. - Try framing your own page from a simple test page you control. It should be refused if you have set the header.
- Review third-party embeds regularly, and remove the ones you no longer use.
Best Practicesβ
- Embed only from sources you trust, and review them over time.
- Always sandbox third-party frames, and add back only what is needed.
- Grant no
allowfeatures by default. - Restrict
frame-srcin your CSP. - Never build an iframe address from visitor input.
- Send
frame-ancestors(andX-Frame-Optionsfor older browsers) on every page that should not be framed. - Check
event.originwith strict equality, and treat message data as untrusted. - Load embeds on demand, and give every frame a title.
- Confirm sensitive actions with more than one click.
Quick Checklistβ
- Every iframe is from a trusted source, over
https - Every third-party iframe has
sandbox -
allowlists only what each frame needs - No iframe address comes from visitor input
-
frame-srclimits where frames may come from - Pages that must not be framed send
frame-ancestors -
messagehandlers checkevent.originexactly -
postMessagecalls use a specifictargetOrigin - Every frame has a
title
Security and Privacy Notesβ
- Embedding shares information. Loading a third-party frame tells that host that the visitor is on your page, and can let it set cookies and track the visitor. For services that need consent, use a click-to-load pattern, or wait for consent first. This is not legal advice, so check the rules that apply to you.
- Do not frame sensitive pages of your own, such as account settings, inside other pages, even your own, unless you must. Fewer places a page can appear means fewer ways to abuse it.
- A frame is not an isolation guarantee. A browser bug or a missing
sandboxcan narrow the gap. Combine layers:sandbox, CSP, and keeping browsers updated. - Test only what you own, or have permission to test. Do not try to frame other people's pages to see what happens.
Global Audience Notesβ
- Embeds are slow and heavy on weak networks, and some providers are blocked in some countries. Make sure your page works if a frame never loads, and offer a plain link as a fallback.
- Many visitors are on shared or mobile devices, where a hijacked click is easy to make. Confirmations for sensitive actions protect them most.
- Screen readers announce the frame title, so write it in the page's language, and describe the content clearly.
- Privacy rules differ by region. Click to load is a simple way to respect them everywhere.
Common Mistakes to Avoidβ
- Embedding without
sandbox. - Using
allow-scriptsandallow-same-origintogether on content from your own origin. - Letting visitors choose the frame address.
- Granting camera or microphone access without a clear need.
- Skipping
frame-ancestorson pages with sensitive actions. - Setting
frame-ancestorsin ametatag, where it is ignored. - Relying on a frame-busting script.
- Checking
event.originwithstartsWithorincludes. - Sending
postMessagewith a target of"*"for sensitive data. - Embedding a provider and never reviewing it again.
Practice Timeβ
- In the Clickjacking Lab, set the slider to zero and click the prize button. What happens? Turn the checkbox on, and try again.
- In the postMessage Lab, try each check. Which checks let the look-alike host through?
- Find the strict-equality check. How many messages does it get wrong?
- Load the messy embeds into the Embed Checker, and fix every problem.
- Open DevTools on a page of yours that has an iframe. Does it have
sandbox,allow, andtitle? - Look at your home page's response headers. Is
frame-ancestorsorX-Frame-Optionspresent? - Write the
Content-Security-Policyline you would use to let only one partner frame your page. - Bonus: add click-to-load to one embed on your own site.
Quick Recapβ
Click a question to check your answer.
1. What are the two directions of iframe risk?
You embed someone else's page (it might harm your visitors), and someone else embeds yours (it might be used to trick your visitors, as in clickjacking).
2. How do you harden an embedded third-party frame?
Trust the source, use sandbox and add back only what is needed, grant no allow features by default, set referrerpolicy, restrict frame-src in your CSP, use https, and load it on demand.
3. What is clickjacking?
An attacker loads your page in a hidden frame over a decoy, so the visitor's click lands on your page's button without them knowing.
4. How do you stop it?
Send the frame-ancestors directive in a CSP header (and X-Frame-Options for older browsers), so your pages cannot be shown in other sites' frames.
5. Why does frame-ancestors need a header?
Browsers ignore it in a CSP set with a meta tag, so it must be sent as an HTTP response header.
6. How should you check a message's origin?
Compare event.origin with an exact value, or a list of exact values, using strict equality. Never use startsWith or includes, and treat event.data as untrusted.
Key Takeawaysβ
- Frames are windows into other pages. Treat each one as a guest with limited powers.
- Sandbox, restrict
allow, setreferrerpolicy, and limitframe-src. - Never let visitors choose a frame address.
- Protect your own pages from being framed with
frame-ancestors, sent as a header. - Check
event.originexactly, and treat message data as untrusted. - Load embeds on demand, and review them regularly.
- Layer your defences, and test only what you own.
Next up: Sandbox Attribute, where you will learn what each sandbox permission does, and how to choose the smallest set.