HTML Iframe and Security

HTML <iframe> is used to embed another webpage inside a page. It is useful for showing videos, maps, and external content, but it can cause security risks like clickjacking and data leakage. Using sandbox and proper restrictions helps keep it safe.

2 views
5 min read
Try It Yourself

Experiment with the code in an interactive editor

What is Iframe?

Iframe lets you show another webpage INSIDE your webpage.

Basic iframe:

1<!-- Embed another website -->
2<iframe src="https://example.com" width="800" height="600"></iframe>
3
4<!-- YouTube video iframe -->
5<iframe width="560" height="315" 
6    src="https://www.youtube.com/embed/dQw4w9WgXcQ" 
7    allowfullscreen>
8</iframe>
9
10<!-- Google Maps iframe -->
11<iframe src="https://www.google.com/maps/embed?pb=..." 
12    width="600" height="450" 
13    allowfullscreen>
14</iframe>

Iframe Security (sandbox attribute)

What is sandbox? It's like putting the embedded page in a "sandbox" where it can't break anything.

Why use sandbox? To protect your users from malicious content in embedded pages.

1<!-- Most secure: blocks EVERYTHING -->
2<iframe src="https://untrusted-site.com" sandbox></iframe>
3
4<!-- Allow specific features -->
5<iframe src="https://trusted-site.com" 
6        sandbox="allow-scripts allow-same-origin allow-forms">
7</iframe>

Sandbox values explained:

Value

What it allows

Risk level

sandbox (alone)

Blocks everything

Most secure

allow-scripts

Allows JavaScript to run

Medium risk

allow-same-origin

Allows content from same website

Medium risk

allow-forms

Allows form submission

Low risk

allow-popups

Allows popup windows

Medium risk

allow-top-navigation

Allows changing the main page URL

High risk

Best practice for external iframes:

1<iframe src="https://external-site.com" 
2        sandbox="allow-scripts allow-same-origin"
3        loading="lazy"
4        title="Embedded content">
5</iframe>