Элемент встроенного фрейма HTML ( <iframe>
) представляет собой вложенный контекст просмотра, встраивающий другую HTML-страницу в текущую.
Каждый встроенный контекст просмотра имеет собственную историю сеанса и документ . Контекст просмотра, в который встроены остальные, называется родительским контекстом просмотра . Самый верхний контекст просмотра - тот, у которого нет родителя - обычно это окно браузера, представленное объектом Window
.
Поскольку каждый контекст просмотра представляет собой полную среду документа, каждый <iframe>
элемент на странице требует увеличения памяти и других вычислительных ресурсов. Хотя теоретически вы можете использовать сколько <iframe>
угодно s, проверьте, нет ли проблем с производительностью.
Категории контента | Контент потока , фразовый контент , встроенный контент, интерактивный контент, осязаемый контент. |
---|---|
Разрешенный контент | Никто. |
Отсутствие тега | None, both the starting and ending tag are mandatory. |
Разрешенные родители | Любой элемент, который принимает встроенный контент. |
Неявная роль ARIA | Нет соответствующей роли |
Разрешенные роли ARIA | application , document , img , none , presentation |
DOM интерфейс | HTMLIFrameElement |
Атрибуты
Этот элемент включает глобальные атрибуты .
allow
- Задает политику функций для
<iframe>
. Политика определяет, какие функции доступны, в<iframe>
зависимости от источника запроса (например, доступ к микрофону, камере, батарее, API общего доступа и т. Д.).
Для получения дополнительной информации и примеров см .: Использование политики функций > Атрибут разрешения iframe . allowfullscreen
- Установите значение,
true
если<iframe>
можно активировать полноэкранный режим путем вызова методаrequestFullscreen ()
. -
Этот атрибут считается устаревшим и переопределяется как
allow="fullscreen"
. allowpaymentrequest
- Установите,
true
если<iframe>
необходимо разрешить перекрестному источнику вызывать API запроса платежа . -
Этот атрибут считается устаревшим и переопределяется как
allow="payment"
. csp
- Содержание политики безопасности применяются для внедренного ресурса. Подробнее см.
HTMLIFrameElement.csp
. height
- Высота фрейма в пикселях CSS. По умолчанию
150
. loading
- Указывает, как браузер должен загружать iframe:
eager
: Немедленно загрузить iframe, независимо от того, находится ли он за пределами видимого окна просмотра (это значение по умолчанию).lazy
: Отложить загрузку iframe до тех пор, пока он не достигнет расчетного расстояния от области просмотра, как определено браузером.
name
- Целевое имя для встроенного контекста просмотра. Его можно использовать в
target
атрибуте элементов<a>
,<form>
или<base>
;formtarget
атрибутом<input>
или<button>
элементов; илиwindowName
параметр в методеwindow.open ()
. referrerpolicy
- Указывает, какой реферер отправлять при выборке ресурса кадра:
no-referrer
: ЗаголовокReferer
не будет отправлен.no-referrer-when-downgrade
(default): TheReferer
header will not be sent to origins without TLS (HTTPS).origin
: The sent referrer will be limited to the origin of the referring page: its scheme, host, and port.origin-when-cross-origin
: The referrer sent to other origins will be limited to the scheme, the host, and the port. Navigations on the same origin will still include the path.same-origin
: A referrer will be sent for same origin, but cross-origin requests will contain no referrer information.strict-origin
: Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP).strict-origin-when-cross-origin
: Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP).unsafe-url
: The referrer will include the origin and the path (but not the fragment, password, or username). This value is unsafe, because it leaks origins and paths from TLS-protected resources to insecure origins.
sandbox
- Applies extra restrictions to the content in the frame. The value of the attribute can either be empty to apply all restrictions, or space-separated tokens to lift particular restrictions:
allow-downloads-without-user-activation
: Allows for downloads to occur without a gesture from the user.allow-downloads
: Allows for downloads to occur with a gesture from the user.allow-forms
: Allows the resource to submit forms. If this keyword is not used, form submission is blocked.allow-modals
: Lets the resource open modal windows.allow-orientation-lock
: Lets the resource lock the screen orientation.allow-pointer-lock
: Lets the resource use the Pointer Lock API.allow-popups
: Allows popups (such aswindow.open()
,target="_blank"
, orshowModalDialog()
). If this keyword is not used, the popup will silently fail to open.allow-popups-to-escape-sandbox
: Lets the sandboxed document open new windows without those windows inheriting the sandboxing. For example, this can safely sandbox an advertisement without forcing the same restrictions upon the page the ad links to.allow-presentation
: Lets the resource start a presentation session.allow-same-origin
: If this token is not used, the resource is treated as being from a special origin that always fails the same-origin policy.allow-scripts
: Lets the resource run scripts (but not create popup windows).allow-storage-access-by-user-activation
: Lets the resource request access to the parent's storage capabilities with the Storage Access API.allow-top-navigation
: Lets the resource navigate the top-level browsing context (the one named_top
).allow-top-navigation-by-user-activation
: Lets the resource navigate the top-level browsing context, but only if initiated by a user gesture.
Notes about sandboxing:- When the embedded document has the same origin as the embedding page, it is strongly discouraged to use both
allow-scripts
andallow-same-origin
, as that lets the embedded document remove thesandbox
attribute — making it no more secure than not using thesandbox
attribute at all. - Sandboxing is useless if the attacker can display content outside a sandboxed
iframe
— such as if the viewer opens the frame in a new tab. Such content should be also served from a separate origin to limit potential damage. - The
sandbox
attribute is unsupported in Internet Explorer 9 and earlier.
src
- The URL of the page to embed. Use a value of
about:blank
to embed an empty page that conforms to the same-origin policy. Also note that programatically removing an<iframe>
's src attribute (e.g. viaElement.removeAttribute()
) causesabout:blank
to be loaded in the frame in Firefox (from version 65), Chromium-based browsers, and Safari/iOS. srcdoc
- Inline HTML to embed, overriding the
src
attribute. If a browser does not support thesrcdoc
attribute, it will fall back to the URL in thesrc
attribute. width
- The width of the frame in CSS pixels. Default is
300
.
Deprecated attributes
These attributes are deprecated and may no longer be supported by all user agents. You should not use them in new content, and try to remove them from existing content.
align
- The alignment of this element with respect to the surrounding context.
frameborder
- The value
1
(the default) draws a border around this frame. The value0
removes the border around this frame, but you should instead use the CSS propertyborder
to control<iframe>
borders. longdesc
- A URL of a long description of the frame's content. Due to widespread misuse, this is not helpful for non-visual browsers.
marginheight
- The amount of space in pixels between the frame's content and its top and bottom borders.
marginwidth
- The amount of space in pixels between the frame's content and its left and right borders.
scrolling
- Indicates when the browser should provide a scrollbar for the frame:
auto
: Only when the frame's content is larger than its dimensions.yes
: Always show a scrollbar.no
: Never show a scrollbar.
Non-standard attributes
mozbrowser
-
See bug 1318532 for exposing this to WebExtensions in Firefox.Makes the
<iframe>
act like a top-level browser window. See Browser API for details.
Available only to WebExtensions.
Scripting
Inline frames, like <frame>
elements, are included in the window.frames
pseudo-array.
With the DOM HTMLIFrameElement
object, scripts can access the window
object of the framed resource via the contentWindow
property. The contentDocument
property refers to the document
inside the <iframe>
, same as contentWindow.document
.
From the inside of a frame, a script can get a reference to its parent window with window.parent
.
Script access to a frame's content is subject to the same-origin policy. Scripts cannot access most properties in other window
objects if the script was loaded from a different origin, including scripts inside a frame accessing the frame's parent. Cross-origin communication can be achieved using Window.postMessage()
.
Positioning and scaling
As a replaced element, the position, alignment, and scaling of the embedded document within the <iframe>
element's box, can be adjusted with the object-position
and object-fit
properties.
Examples
A simple <iframe>
An <iframe>
in action. After creating the frame, when the user clicks a button, its title is displayed in an alert.
HTML
<iframe src="https://mdn-samples.mozilla.org/snippets/html/iframe-simple-contents.html"
title="iframe Example 1" width="400" height="300">
</iframe>
Result
Accessibility concerns
People navigating with assistive technology such as a screen reader can use the title
attribute on an <iframe>
to label its content. The title's value should concisely describe the embedded content:
<iframe title="Wikipedia page for Avocados" src="https://en.wikipedia.org/wiki/Avocado"></iframe>
Without this title, they have to navigate into the <iframe>
to determine what its embedded content is. This context shift can be confusing and time-consuming, especially for pages with multiple <iframe>
s and/or if embeds contain interactive content like video or audio.
Specifications
Specification | Status | Comment |
---|---|---|
Referrer Policy The definition of 'referrerpolicy attribute' in that specification. |
Candidate Recommendation | Added the referrerpolicy attribute. |
HTML Living Standard The definition of '<iframe>' in that specification. |
Living Standard | |
HTML5 The definition of '<iframe>' in that specification. |
Recommendation | |
HTML 4.01 Specification The definition of '<iframe>' in that specification. |
Recommendation | |
Screen Orientation API | Working Draft | Adds allow-orientation-lock to the sandbox attribute. |
Browser compatibility
BCD tables only load in the browser