无法使用 Javascript 与不同来源的 iFrame 进行交互以获取它的大小;唯一的方法是使用window.postMessage 并将targetOrigin 设置为您的域或来自iFrame 源的通配符*。您可以代理不同源站点的内容并使用srcdoc,但这被认为是一种hack,它不适用于 SPA 和许多其他更动态的页面。
同源 iFrame 大小
假设我们有两个同源 iFrame,一个是短高度,一个是固定宽度:
<!-- iframe-short.html -->
<head>
<style type="text/css">
html, body { margin: 0 }
body {
width: 300px;
}
</style>
</head>
<body>
<div>This is an iFrame</div>
<span id="val">(val)</span>
</body>
还有一个长高的iFrame:
<!-- iframe-long.html -->
<head>
<style type="text/css">
html, body { margin: 0 }
#expander {
height: 1200px;
}
</style>
</head>
<body>
<div>This is a long height iFrame Start</div>
<span id="val">(val)</span>
<div id="expander"></div>
<div>This is a long height iFrame End</div>
<span id="val">(val)</span>
</body>
我们可以使用iframe.contentWindow.document 获取load 事件的 iFrame 大小,我们将使用postMessage 将其发送到父窗口:
<div>
<iframe id="iframe-local" src="iframe-short.html"></iframe>
</div>
<div>
<iframe id="iframe-long" src="iframe-long.html"></iframe>
</div>
<script>
function iframeLoad() {
window.top.postMessage({
iframeWidth: this.contentWindow.document.body.scrollWidth,
iframeHeight: this.contentWindow.document.body.scrollHeight,
params: {
id: this.getAttribute('id')
}
});
}
window.addEventListener('message', ({
data: {
iframeWidth,
iframeHeight,
params: {
id
} = {}
}
}) => {
// We add 6 pixels because we have "border-width: 3px" for all the iframes
if (iframeWidth) {
document.getElementById(id).style.width = `${iframeWidth + 6}px`;
}
if (iframeHeight) {
document.getElementById(id).style.height = `${iframeHeight + 6}px`;
}
}, false);
document.getElementById('iframe-local').addEventListener('load', iframeLoad);
document.getElementById('iframe-long').addEventListener('load', iframeLoad);
</script>
我们将为两个 iFrame 获得正确的宽度和高度;您可以在线查看here 并查看截图here。
不同来源的 iFrame 大小hack(不推荐)
这里描述的方法是一个hack,如果绝对必要并且没有其他方法,应该使用它; 它对大多数动态生成的页面和 SPA 不起作用。该方法使用代理获取页面 HTML 源代码以绕过 CORS 策略(cors-anywhere 是一种创建简单 CORS 代理服务器的简单方法,它有一个在线演示 https://cors-anywhere.herokuapp.com)然后注入该 HTML 的 JS 代码使用 postMessage 并将 iFrame 的大小发送到父文档。它甚至可以处理 iFrame resize(结合 iFrame width: 100%)事件并将 iFrame 大小发送回父级。
patchIframeHtml:
修补 iFrame HTML 代码并注入自定义 Javascript 的函数,该 Javascript 将使用 postMessage 将 iFrame 大小发送到 load 和 resize 上的父级。如果 origin 参数有值,则 HTML <base/> 元素将使用该原始 URL 附加到头部,因此,像 /some/resource/file.ext 这样的 HTML URI 将被 iFrame 内的原始 URL 正确获取。
function patchIframeHtml(html, origin, params = {}) {
// Create a DOM parser
const parser = new DOMParser();
// Create a document parsing the HTML as "text/html"
const doc = parser.parseFromString(html, 'text/html');
// Create the script element that will be injected to the iFrame
const script = doc.createElement('script');
// Set the script code
script.textContent = `
window.addEventListener('load', () => {
// Set iFrame document "height: auto" and "overlow-y: auto",
// so to get auto height. We set "overlow-y: auto" for demontration
// and in usage it should be "overlow-y: hidden"
document.body.style.height = 'auto';
document.body.style.overflowY = 'auto';
poseResizeMessage();
});
window.addEventListener('resize', poseResizeMessage);
function poseResizeMessage() {
window.top.postMessage({
// iframeWidth: document.body.scrollWidth,
iframeHeight: document.body.scrollHeight,
// pass the params as encoded URI JSON string
// and decode them back inside iFrame
params: JSON.parse(decodeURIComponent('${encodeURIComponent(JSON.stringify(params))}'))
}, '*');
}
`;
// Append the custom script element to the iFrame body
doc.body.appendChild(script);
// If we have an origin URL,
// create a base tag using that origin
// and prepend it to the head
if (origin) {
const base = doc.createElement('base');
base.setAttribute('href', origin);
doc.head.prepend(base);
}
// Return the document altered HTML that contains the injected script
return doc.documentElement.outerHTML;
}
getIframeHtml:
如果设置了useProxy 参数,则使用代理获取页面 HTML 绕过 CORS 的函数。发送尺寸数据时,可以有额外的参数传递给postMessage。
function getIframeHtml(url, useProxy = false, params = {}) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
// If we use a proxy,
// set the origin so it will be placed on a base tag inside iFrame head
let origin = useProxy && (new URL(url)).origin;
const patchedHtml = patchIframeHtml(xhr.responseText, origin, params);
resolve(patchedHtml);
}
}
// Use cors-anywhere proxy if useProxy is set
xhr.open('GET', useProxy ? `https://cors-anywhere.herokuapp.com/${url}` : url, true);
xhr.send();
});
}
消息事件处理函数与"Same origin iFrame size"中完全一样。
我们现在可以在 iFrame 中加载一个跨域域,并注入我们的自定义 JS 代码:
<!-- It's important that the iFrame must have a 100% width
for the resize event to work -->
<iframe id="iframe-cross" style="width: 100%"></iframe>
<script>
window.addEventListener('DOMContentLoaded', async () => {
const crossDomainHtml = await getIframeHtml(
'https://en.wikipedia.org/wiki/HTML', true /* useProxy */, { id: 'iframe-cross' }
);
// We use srcdoc attribute to set the iFrame HTML instead of a src URL
document.getElementById('iframe-cross').setAttribute('srcdoc', crossDomainHtml);
});
</script>
我们将让 iFrame 调整到其内容的全高,即使使用 overflow-y: auto 作为 iFrame 主体(它应该是 overflow-y: hidden,所以我们不会在调整大小时滚动条闪烁)。
您可以在线查看here。
再次注意到这是一种黑客攻击,应该避免;我们不能访问Cross-Origin iFrame 文档,也不能注入任何东西。