HTML Tutorial · HTML5 Features · Lesson 28 of 34
HTML Iframes and the sandbox Attribute
Embed other pages safely with iframe, sandbox, allow, title and lazy loading.
Embedding with iframe
<iframe> shows another page inside yours: maps, videos, payment fields, previews.
<iframe src="https://www.openstreetmap.org/export/embed.html" title="Map of the office" width="400" height="300" loading="lazy"></iframe>
- Always add a
titledescribing the content, for screen-reader users. - Use
loading="lazy"for iframes below the fold.
sandbox: restrict what the frame can do
An empty sandbox attribute blocks scripts, forms, pop-ups, top-level navigation and same-origin access. Add tokens to allow only what's needed: allow-scripts, allow-forms, allow-popups, allow-same-origin...
The example embeds untrusted HTML with srcdoc twice: once sandboxed without scripts, once allowing them.
<p>Sandboxed, no scripts:</p>
<iframe sandbox title="Untrusted content without scripts" width="320" height="70"
srcdoc="<p>Hello <b>from the frame</b></p><script>document.body.append(' Script ran!')</script>"></iframe>
<p>Sandboxed with allow-scripts:</p>
<iframe sandbox="allow-scripts" title="Untrusted content with scripts" width="320" height="70"
srcdoc="<p>Hello <b>from the frame</b></p><script>document.body.append(' Script ran!')</script>"></iframe>
Never combine allow-scripts and allow-same-origin for content from your own origin: the framed page could then remove its own sandbox.
allow: browser features
The allow attribute grants features to the frame, such as allow="fullscreen; camera". By default, sensitive features are not available to cross-origin frames.
Stop others from framing you
To prevent clickjacking, your server should send Content-Security-Policy: frame-ancestors 'self' (or X-Frame-Options: DENY) so other sites can't embed your pages. This is an HTTP header, not HTML.
Test yourself
What does an empty sandbox attribute on an iframe do?
Nothing; you must list restrictionsApplies all restrictions: no scripts, forms, pop-ups or same-origin accessHides the iframeAllows everything except cookies
Show answer
Answer: Applies all restrictions: no scripts, forms, pop-ups or same-origin access
An empty sandbox is the most restrictive; tokens re-enable specific capabilities.