Chapter 17 of 26

Iframes & Embedding Content

In the Audio & Video chapter, we played our own video files. But what if the video lives on YouTube, or you want to show a Google Map of your college, a payment form from Razorpay, or a code playground from CodePen? You can't copy those pages into your HTML. Instead, you open a small "window" in your page and load the other page inside it.

That window is the <iframe> element. It's one of the most useful elements in HTML, and also one of the most security-sensitive, so in this chapter we'll learn both how to use it and how to use it safely.

An <iframe> (inline frame) embeds another, complete HTML document inside the current page. The embedded page gets its own separate browsing context: its own document, its own scripts, its own styles and its own history.

Think of a TV inside a shop window. The shop (your page) decides where the TV goes and how big it is, but what plays on the TV is controlled by the TV channel (the other website).


Basic Syntax

<iframe src="notice.html" title="College notice board" width="400" height="160"></iframe>
AttributeMeaning
srcURL of the page to load inside the frame
titleA short description for screen readers. Every iframe should have one
width, heightSize in CSS pixels. Defaults are 300 × 150 if you leave them out

A few facts about how an iframe behaves:

  • It is an inline element (recall the Block vs Inline Elements chapter), so two iframes sit side by side if there's room.

  • Browsers draw a thin inset border around it by default. Remove it with CSS (border: none;), not with old HTML attributes.

  • The content between <iframe> and </iframe> is ignored by modern browsers, so leave it empty.

Why is title so important? A screen reader announces an iframe as a "frame" and reads its title. Without it, a blind user hears just "frame" and has no idea whether it contains a video, a map or an advert. Accessibility checkers report a missing iframe title as an error.


A Complete Example

Let's build a small "college portal". Create three files in the same folder.

notice.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Notice Board</title>
</head>
<body>
  <h2>Notice Board</h2>
  <p>Mid-semester exams start on 10 March.</p>
</body>
</html>

timetable.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Timetable</title>
</head>
<body>
  <h2>Timetable</h2>
  <p>Monday: DBMS, OS, CN</p>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Iframe Demo</title>
</head>
<body>
  <h1>College Portal</h1>

  <nav>
    <a href="notice.html" target="viewer">Notices</a> |
    <a href="timetable.html" target="viewer">Timetable</a>
  </nav>

  <iframe src="notice.html" name="viewer" title="College information viewer"
          width="400" height="160"></iframe>

  <iframe srcdoc="<p>Hello from <strong>srcdoc</strong>!</p>"
          title="Inline greeting" width="300" height="80"></iframe>
</body>
</html>

Open index.html and you'll see:

College Portal
Notices | Timetable
┌─────────────────────────────┐
│ Notice Board                │
│                             │  ┌─────────────────────┐
│ Mid-semester exams start    │  │ Hello from srcdoc!  │
│ on 10 March.                │  │                     │
└─────────────────────────────┘  └─────────────────────┘

The two frames sit next to each other (they're inline), each with a thin grey border. Now click Timetable: only the first frame changes to show the timetable, while the heading and links stay put. Let's see why.

Targeting an Iframe with name

In the Links chapter, you saw target="_blank". The target attribute can also hold the name of an iframe. Because our iframe has name="viewer", any link with target="viewer" opens inside that frame instead of replacing the whole page. Forms can use target the same way.

srcdoc: HTML Written Inline

Instead of a URL, srcdoc contains the HTML of the embedded page directly. If both src and srcdoc are present, srcdoc wins. It's handy for previews, like the "result" panel of an online code editor. Inside the attribute, use single quotes for any attribute values so they don't end the double-quoted srcdoc value early.


Embedding a YouTube Video

On YouTube, click Share → Embed and you get code like this (shown here slightly tidied, with VIDEO_ID in place of the real ID):

<iframe width="560" height="315"
        src="https://www.youtube.com/embed/VIDEO_ID"
        title="YouTube video player"
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
        referrerpolicy="strict-origin-when-cross-origin"
        allowfullscreen></iframe>

Let's read it piece by piece:

PartMeaning
/embed/VIDEO_IDA special player-only page. The normal /watch?v= page can't be framed
allow="..."Which browser features the frame may use (autoplay, picture-in-picture, etc.)
referrerpolicyHow much of your page's URL is sent to YouTube
allowfullscreenLets the full-screen button work

The real embed code also contains frameborder="0". That attribute is obsolete in HTML (validators report it); use CSS border: none; instead.

Privacy tip: YouTube also offers https://www.youtube-nocookie.com/embed/VIDEO_ID, a "privacy-enhanced mode". YouTube says that in this mode, views of the embedded video don't influence the visitor's recommendations and browsing experience on YouTube. It reduces tracking, but does not remove it completely.

Embedding Google Maps

In Google Maps, choose Share → Embed a map and copy the code. It's the same idea: an iframe whose src points to a special /maps/embed?pb=... URL, usually with loading="lazy". Always add a meaningful title, like title="Map of our college campus".


Lazy Loading Iframes

Every iframe is a whole web page with its own HTML, CSS, JavaScript and images. A YouTube embed alone can download well over a megabyte. If the iframe is far down the page, don't load it until the user scrolls near it:

<iframe src="https://www.youtube.com/embed/VIDEO_ID" title="Lecture 1: Arrays"
        width="560" height="315" loading="lazy" allowfullscreen></iframe>

loading can be eager (default, load immediately) or lazy. Don't lazy-load an iframe that is visible as soon as the page opens, because it will just appear later than it should.


Why Some Websites Refuse to Load in an Iframe

Try this:

<iframe src="https://www.google.com/" title="Google" width="400" height="200"></iframe>

Instead of Google's home page you get an empty grey box with a "broken page" icon, and the browser's developer console reports that the page refused to be displayed in a frame. Google's server sends this HTTP response header:

X-Frame-Options: SAMEORIGIN

meaning "only pages from my own origin may frame me". The modern way to say the same thing is the Content Security Policy header frame-ancestors:

Content-Security-Policy: frame-ancestors 'self'

Why would a site do this? Because of clickjacking:

1. An attacker makes a page: "Click here to win a free phone!"
2. Underneath, invisibly (opacity 0), they frame your bank's "Transfer money" page
3. They position the frame so the real "Confirm" button sits exactly under "Click here"
4. You click the fake button → you actually clicked the bank's button

Banks, email providers and login pages therefore forbid framing. Sites that want to be embedded (YouTube, Maps, CodePen) provide special embed URLs that allow it.

The iframe cannot override this. Whether a page can be framed is the embedded site's decision, made with HTTP headers on its server, not something your HTML controls.

The Same-Origin Policy

Even when a cross-origin page loads, your JavaScript can't reach inside it and read its content, and its JavaScript can't read yours. An origin is scheme + host + port (for example https://cslearningportal.com:443). Only pages with the same origin can access each other's documents. Cross-origin frames talk to their parent only through a controlled message channel (postMessage() in JavaScript).


The sandbox Attribute

What if you embed a page you don't fully trust, like code written by your users? The sandbox attribute locks the frame down:

<iframe sandbox title="Fully sandboxed" width="250" height="80"
        srcdoc="<p id='msg'>Scripts are blocked</p><script>document.getElementById('msg').textContent = 'Scripts ran!';</script>"></iframe>

<iframe sandbox="allow-scripts" title="Scripts allowed" width="250" height="80"
        srcdoc="<p id='msg'>Scripts are blocked</p><script>document.getElementById('msg').textContent = 'Scripts ran!';</script>"></iframe>

Result in the browser:

┌──────────────────────┐ ┌──────────────────────┐
│ Scripts are blocked  │ │ Scripts ran!         │
└──────────────────────┘ └──────────────────────┘

Both frames contain identical code. The first has an empty sandbox, so its script never runs. The second lifts just one restriction with allow-scripts.

An empty sandbox applies every restriction: no scripts, no form submission, no popups, no downloads, no navigating the top page, and the content is treated as coming from a unique, opaque origin (so it can't read cookies or storage of its real site). You then add back only what you need with space-separated tokens. The most common ones:

TokenAllows
allow-scriptsRunning JavaScript
allow-formsSubmitting forms
allow-same-originTreating the content as its real origin (cookies, storage)
allow-popupsOpening new windows (target="_blank", window.open())
allow-modalsalert(), confirm(), prompt()
allow-downloadsDownloading files
allow-top-navigationChanging the URL of the main page

Danger: never combine allow-scripts and allow-same-origin for a page from your own origin. Its script could then reach up into your page and simply remove the sandbox attribute, making the sandbox useless.


The allow Attribute (Permissions Policy)

sandbox is about general abilities. allow controls access to powerful browser features such as the camera, microphone, location, full screen and autoplay. By default, a cross-origin iframe can't use most of these.

<!-- A video-call widget that needs camera, mic and full screen -->
<iframe src="https://meet.example.com/room/42" title="Video call"
        width="640" height="400"
        allow="camera; microphone; fullscreen"></iframe>

Give each embed only the features it really needs. allowfullscreen is an older attribute that is now defined as the same thing as allow="fullscreen *"; both work.


Obsolete Iframe Attributes

You will still see these in old tutorials and copy-pasted embed codes. Replace them with CSS:

ObsoleteUse instead
frameborder="0"CSS border: none;
scrolling="no"CSS overflow on the embedded page
marginwidth, marginheightCSS margin on the embedded page's body
alignCSS layout

The old <frameset> and <frame> elements (which split the whole window into frames) are obsolete: they are no longer valid HTML, and browsers support them only so that very old sites keep working. Don't confuse them with <iframe>, which is fully supported.


<embed> and <object>

HTML has two older embedding elements:

<object data="syllabus.pdf" type="application/pdf" width="600" height="400">
  <p>Can't show the PDF here. <a href="syllabus.pdf">Download the syllabus</a>.</p>
</object>

<embed src="syllabus.pdf" type="application/pdf" title="Course syllabus" width="600" height="400">
ElementNotes
<iframe>Embeds another web page. The modern, preferred choice
<object>Embeds an external resource (often a PDF); supports fallback content inside it
<embed>Void element (no closing tag, no fallback); originally for plugins

They were mainly used for plugins like Flash, which browsers no longer support. Today, use <video>/<audio> for media, <img> for images, and <iframe> for pages. For PDFs, a plain download link is the most reliable choice, because many mobile browsers can't display PDFs inline.


Iframes and Responsiveness

width="560" is too wide for many phones. The usual fix, which you'll meet in CSS, is to make the iframe width: 100% and set its shape with the CSS property aspect-ratio: 16 / 9. Keep the width and height attributes in the HTML anyway, so the browser knows the shape before CSS loads.


Common Mistakes

  • Missing title. Screen-reader users can't tell what the frame is.

  • Framing a normal page URL like youtube.com/watch?v=... or a bank site. Use the official embed URL; many sites forbid framing with X-Frame-Options or CSP frame-ancestors.

  • Using frameborder and scrolling. Obsolete; use CSS.

  • Too many iframes on one page. Each one is a full page load. Use loading="lazy" for those below the fold.

  • sandbox="allow-scripts allow-same-origin" on same-origin content. This cancels the sandbox.

  • Expecting to read a cross-origin iframe with JavaScript. The same-origin policy forbids it.


Interview Questions

Q1. You put <iframe src="https://www.google.com"> on your page and it shows a blank box. Why?

Google's server sends X-Frame-Options: SAMEORIGIN, which tells the browser not to display the page inside a frame on another origin. The modern equivalent is Content-Security-Policy: frame-ancestors. Sites do this to prevent clickjacking. Your HTML cannot override it.

Q2. What is clickjacking?

An attack where a victim site is loaded in an invisible iframe on top of (or under) an attacker's page, positioned so that when the user clicks something harmless-looking, they actually click a button on the victim site. Defence: the victim site refuses to be framed using frame-ancestors or X-Frame-Options.

Q3. What does an empty sandbox attribute do?

It applies all restrictions: scripts, forms, popups, modals, downloads and top-level navigation are blocked, and the content gets a unique opaque origin. Tokens like allow-scripts lift individual restrictions.

Q4. Difference between src and srcdoc?

src is a URL to load; srcdoc contains the HTML content itself. If both are present, srcdoc is used.

Q5. Difference between sandbox and allow?

sandbox restricts general capabilities (scripts, forms, popups, origin). allow is the Permissions Policy for the frame, granting access to specific browser features like camera, microphone, geolocation, autoplay and full screen.


Conclusion

An <iframe> embeds a whole separate web page inside yours. Give it a title, load it lazily when it's off-screen, and grant it only the permissions it needs.

  • Default size is 300 × 150; set width/height and style the border with CSS.

  • Links and forms can load into an iframe using its name as their target.

  • Use official embed URLs for YouTube and Maps; many sites block framing to prevent clickjacking.

  • sandbox locks down untrusted content; allow grants specific features.

  • frameborder, scrolling and <frameset> are obsolete.

Next, in The Head Element & Meta Tags, we'll look at the invisible part of every page: the information that browsers, search engines and social media sites read from <head>.