HTML & CSSMedium
What is an <iframe>?
An <iframe> (inline frame) embeds another HTML document inside the current page, for example a YouTube video, a map, a payment widget or a sandboxed preview. The embedded page has its own window, DOM, CSS and JavaScript, isolated from the parent by the same-origin policy.
Key attributes
src/srcdoc: the URL to load, or inline HTML.title: required for accessibility; it names the frame for screen readers.loading="lazy": defer offscreen frames.sandbox: applies strict restrictions (no scripts, forms, popups, same-origin access) that you selectively relax:sandbox="allow-scripts allow-forms".allow: permissions policy for features such asfullscreen,camera,clipboard-write.referrerpolicy: controls what referrer the frame receives.
Security
- Embedding others: always sandbox untrusted content. Never combine
allow-scriptswithallow-same-originfor same-origin content, because the frame could then remove its own sandbox. - Being embedded (clickjacking): protect your own pages with
Content-Security-Policy: frame-ancestors 'self'(or the olderX-Frame-Options: DENY).
Communication
Cross-origin frames talk to the parent only via window.postMessage; always check event.origin on the receiving side.
Downsides
Each iframe is a full document, so they cost memory and load time, and they can hurt performance if overused.
Code example
html
1<!doctype html>2<html lang="en">3<body style="font-family: system-ui">4 <h1>Sandboxed preview</h1>5 <iframe6 id="preview"7 title="User code preview"8 sandbox="allow-scripts"9 loading="lazy"10 style="width:100%;height:120px;border:2px solid #0b1020;border-radius:8px"11 srcdoc="<button onclick="parent.postMessage('clicked', '*')">Click inside the frame</button>"12 ></iframe>13 <p>Messages from frame: <output id="log">none</output></p>14 <script>15 let count = 0;16 window.addEventListener("message", (event) => {17 // A sandboxed srcdoc frame has an opaque origin, reported as "null".18 // For real third-party frames, compare against the exact origin you expect.19 if (event.source !== document.getElementById("preview").contentWindow) return;20 document.getElementById("log").textContent = `${event.data} (${++count})`;21 });22 </script>23</body>24</html>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.