Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
The iframe tag allows you to embed content from other origins (other sites) into your web page.
An iframe creates a new nested browsing context. This means anything in the iframe does not interfere with the parent page, and vice versa. JavaScript and CSS do not “leak” between iframes and the parent page.
Basic Usage
<iframe src="page.html"></iframe>
You can load an absolute URL:
<iframe src="https://example.com/page.html"></iframe>
Dimensions
Set width and height, or the iframe will use defaults (300 x 150 pixels):
<iframe src="page.html" width="800" height="400"></iframe>
The srcdoc Attribute
Instead of loading an external page, you can specify inline HTML:
<iframe srcdoc="<p>This content is embedded directly</p>"></iframe>
Security with sandbox
The sandbox attribute limits what the iframe can do.
An empty sandbox is most restrictive:
<iframe src="page.html" sandbox=""></iframe>
You can selectively enable features by adding values:
<iframe src="page.html" sandbox="allow-scripts allow-forms"></iframe>
Common sandbox values:
allow-forms- Allow form submissionallow-modals- Allow modal dialogs (includingalert())allow-popups- Allow popups (window.open(),target="_blank")allow-scripts- Allow JavaScript executionallow-same-origin- Treat as same originallow-top-navigation- Allow navigation of the parent page
The allow Attribute
The allow attribute controls access to browser features:
<iframe src="page.html" allow="camera; microphone; fullscreen"></iframe>
Common permissions:
camera- Access the cameramicrophone- Access the microphonefullscreen- Allow fullscreen modegeolocation- Access locationautoplay- Allow media autoplay
Common Use Cases
Iframes are commonly used for:
- Embedding YouTube videos
- Including code playgrounds (CodePen, CodeSandbox)
- Embedding maps
- Loading third-party widgets
- Displaying external content safely
Example: Embedding a YouTube Video
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/VIDEO_ID"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope"
allowfullscreen>
</iframe>
Referrer Policy
Control what referrer information is sent when loading the iframe:
<iframe src="page.html" referrerpolicy="no-referrer"></iframe>
Common values:
no-referrer- Send no referrer informationorigin- Send only the origin (domain)same-origin- Send referrer only for same-origin requests