Iframe

On this page 7

An iframe, short for inline frame, is the HTML element iframe that embeds a separate, fully independent web document inside the current page. The embedded document has its own URL, its own DOM, its own scripts and styles, and its own browsing context, so it behaves like a small browser window placed within the layout.

In HTML and web development, iframes are the standard way to include third-party content such as video players, maps, payment fields, advertisements and social media posts. Because they connect two documents that may come from different origins, iframes are closely tied to browser security, privacy and performance.

How an iframe embeds another document

When the browser encounters an iframe, it creates a nested browsing context: a separate document with its own window object, history entry and rendering. The src attribute points to the URL to load, while the srcdoc attribute can supply inline HTML directly. Without explicit dimensions, an iframe renders at a default size of 300 by 150 CSS pixels.

The same-origin policy governs how the parent page and the embedded document interact. If both share the same scheme, host and port, scripts can access each other’s DOM. If the origins differ, direct access is blocked, and the two documents can communicate only through the postMessage API, which sends messages that the receiver must validate by checking the sender’s origin.

AttributePurposeTypical value or note
srcURL of the embedded documentAbsolute or relative URL
srcdocInline HTML content instead of a URLTakes precedence over src
titleAccessible name for assistive technologyShort description of the content
sandboxApplies strict restrictionsEmpty value or a list of allow tokens
allowPermissions policy for powerful featuresfullscreen, camera, geolocation, payment
loadingControls when the frame loadslazy defers off-screen frames
referrerpolicyControls the referrer sent with the requeststrict-origin-when-cross-origin
Key iframe attributes

Security controls for iframes

Iframes create risks in two directions. A page that embeds untrusted content can expose users to malicious scripts or deceptive forms, and a page that can be embedded by others is vulnerable to clickjacking, where an attacker overlays an invisible frame to trick users into clicking hidden buttons.

The sandbox attribute protects the embedding page. An empty sandbox disables scripts, forms, pop-ups and top-level navigation and treats the content as coming from a unique origin. Specific tokens such as allow-scripts or allow-forms then grant only the needed capabilities. Combining allow-scripts with allow-same-origin for same-origin content effectively removes the sandbox, so that pairing should be avoided.

MechanismSet byProtects against
sandbox attributeEmbedding pageUntrusted scripts and navigation inside the frame
allow attributeEmbedding pageUnwanted access to camera, microphone or location
CSP frame-ancestorsEmbedded site, via response headerBeing framed by unauthorized sites
X-Frame-OptionsEmbedded site, via response headerClickjacking; older and less flexible than CSP
CSP frame-srcEmbedding pageLoading frames from unapproved origins
Mechanisms that control framing

Modern browsers also apply storage partitioning to third-party frames, so cookies and storage inside an embedded widget are separated per top-level site. This limits cross-site tracking but can break older embedded login flows that relied on shared third-party cookies.

Iframe compared with other embedding methods

An iframe is not the only way to place external content in a page. The right choice depends on how much isolation, control and integration the content needs.

MethodIsolationBest forDrawback
IframeFull separate documentThird-party widgets, payments, mapsHeavier, harder to size and style
object and embed elementsPlugin-style contentPDFs and legacy mediaLimited control and inconsistent support
Script-injected widgetNone, runs in the pageDeep integration with the layoutFull access to the page and its data
Web components with shadow DOMStyle encapsulation onlyReusable components from the same appScripts are not isolated
Server-side include or fetchNone, content mergedTrusted first-party fragmentsNo protection from untrusted code
Iframe and alternative embedding methods

The main advantage of an iframe is strong isolation by default: a crash, style conflict or script error inside the frame rarely affects the host page. The cost is weaker integration, because the parent cannot easily style the content or automatically size the frame to its height.

Performance and accessibility considerations

Each iframe loads a complete document with its own network requests, scripts and rendering work. Several embedded videos, maps or ad slots can noticeably slow a page and harm Core Web Vitals such as Largest Contentful Paint and Interaction to Next Paint.

  • Use loading set to lazy for frames below the fold, so they load only when the user scrolls near them.
  • Reserve space with width and height or an aspect ratio, to avoid layout shifts when the frame appears.
  • Use a facade for heavy embeds such as video players: show a lightweight preview image and load the real iframe on click.
  • Always add a title attribute that describes the content, because screen readers announce frames by this name.
  • Avoid deprecated attributes such as frameborder and scrolling; use CSS for borders and overflow instead.

Common iframe problems

Many iframe issues come from the boundary between two documents rather than from the element itself.

ProblemCauseSolution
Frame shows a blank or refused pageTarget site forbids framingRespect the policy or use the provider’s embed URL
Content is cut off or scrollsFrame height does not match contentSend the height via postMessage and resize
Messages from the frame are ignoredOrigin not checked or mismatchedValidate event.origin and target a specific origin
Embedded login stops workingThird-party cookies are partitioned or blockedUse top-level redirects or storage access requests
Screen reader announces only frameMissing title attributeAdd a descriptive title
Typical iframe problems and solutions

The simple explanation

An iframe is a window inside a web page that shows another web page. When a news article includes a video player or a map from another service, that content usually sits in an iframe.

The page inside the window is kept separate from the page around it, a bit like a picture frame on a wall that holds a photo from somewhere else. This separation keeps both pages safer, but it also makes them harder to fit together perfectly.

How it is used in practice

An online shop for outdoor equipment needs to accept card payments without handling card numbers on its own servers. Its payment provider supplies hosted input fields that the checkout page embeds as small iframes from the provider’s domain.

Because the frames come from a different origin, the shop’s scripts cannot read the card data, which reduces the shop’s security and compliance burden. The provider’s frames send only a confirmation token back to the page through postMessage, and the shop’s code accepts messages only from the provider’s exact origin.

The developer also adds descriptive titles for screen readers and reserves fixed heights to prevent layout shifts. Customers see one seamless checkout form, while sensitive data never touches the shop’s own code.