The iframe element permits to embed another HTML page in a page creating a new browsing context (ie a new environment is created for the loading of this page).
This new environment is nested (meaning that it's inside the environment of the page where the iframe appears) creating a hierarchy of environment (known also as browsing context).
<iframe
src="https://datacadamia.com/_export/code/web/html/iframe?codeblock=1">
</iframe>
<p>Iframe !</p>
Iframe are used mostly to embed third-party content such as:
The default height is the default height of the html element which is 150px
You can sandbox an iframe.
<iframe sandbox="allow-same-origin allow-forms allow-scripts allow-downloads"> </iframe>
The padding of the first descendant phrasing element (such as p or pre but not div) are added to the HTML element in a iframe context.
Example:
<p style="padding:10px">A div with a padding that will be propagated to the HTML element</p>
iFrameElement.contentWindow.document
// Note that iframe.contentDocument == iframe.contentWindow.document
let parentDocument = parent.document
let iframeElement = window.frameElement;
let isIframe = window.self !== window.top;
console.log(isIframe);
for (var i = 0; i < window.parent.frames.length; i++) {
let currentFrame = window.parent.frames[i];
if (currentFrame === window.self) {
console.log(`This window is the frame at the index (${i}) in the stack`);
}
}
This demo updates the height of the iframe to the height of the internal window.
This example is just for demonstration purpose because you can also achieve the same with the height css attribute, namely.
height:auto;
window.addEventListener("load", function () {
// Select the iframe element with the class webCode
const webCodeIFrames = document.querySelectorAll("iframe.webcode-combo");
// Set the height of the iframe to be the height of the internal iframe
if (webCodeIFrames != null) {
for (let i = 0; i < webCodeIFrames.length; i++) {
const webCodeIFrame = webCodeIFrames[i];
const height = webCodeIFrame.getAttribute('height');
if (height == null) {
let htmlIFrameElement = webCodeIFrame.contentWindow.document.querySelector("html");
let calculatedHeight = htmlIFrameElement.offsetHeight;
let defaultHtmlElementHeight = 150;
if (calculatedHeight === defaultHtmlElementHeight) {
// body and not html because html has a default minimal height of 150
calculatedHeight = webCodeIFrame.contentWindow.document.querySelector("body").offsetHeight;
// After setting the height, there is a recalculation and the padding of a descendant phrasing content element
// may ends up in the html element. The below code corrects that
requestAnimationFrame(function() {
if (calculatedHeight !== htmlIFrameElement.offsetHeight) {
webCodeIFrame.height = htmlIFrameElement.offsetHeight;
}
});
}
webCodeIFrame.height = calculatedHeight;
}
}
}
});