javascript - 如何在没有纵横比假设的情况下使 iframe 响应?
问题描述
如何在不假设纵横比的情况下使 iframe 响应?例如,内容可能具有任何宽度或高度,这在渲染之前是未知的。
请注意,您可以使用 Javascript。
例子:
<div id="iframe-container">
<iframe/>
</div>
调整它的大小iframe-container
,使其内容在没有额外空间的情况下几乎无法放入其中,换句话说,有足够的空间容纳内容,因此可以在不滚动的情况下显示它,但没有多余的空间。Container 完美地包裹了 iframe。
这显示了如何使 iframe 响应,假设内容的纵横比为 16:9。但是在这个问题中,纵横比是可变的。
解决方案
无法使用 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>
我们可以使用我们将发送到父窗口的load
事件获取 iFrame 大小:iframe.contentWindow.document
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 获得适当的宽度和高度;您可以在此处在线查看并在此处查看屏幕截图。
不同来源的 iFrame 大小破解(不推荐)
此处描述的方法是一种hack,如果绝对必要并且没有其他方法,则应该使用它;它不适用于大多数动态生成的页面和 SPA。该方法使用代理获取页面 HTML 源代码以绕过 CORS 策略(cors-anywhere
这是一种创建简单 CORS 代理服务器的简单方法,它有一个在线演示https://cors-anywhere.herokuapp.com
)然后将 JS 代码注入该 HTML 以使用postMessage
并发送大小iFrame 到父文档。它甚至处理 iFrame resize
(与 iFrame 结合width: 100%
)事件并将 iFrame 大小发送回父级。
patchIframeHtml
:
修补 iFrame HTML 代码并注入自定义 Javascript 的函数,该 Javascript 将用于postMessage
将 iFrame 大小发送到父级 onload
和 on resize
。如果参数有值origin
,则 HTML<base/>
元素将使用该原始 URL 附加到头部,因此,HTML URI 之类/some/resource/file.ext
的将被 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
这样我们不会在调整大小时滚动条闪烁)。
你可以在这里在线查看。
再次注意到这是一个 hack,应该避免它;我们无法访问跨域iFrame 文档,也无法注入任何东西。
推荐阅读
- swift - 无法在 IOS 中禁用 SSL 验证
- java - 一般编程新手(Java)。我应该如何修复这些错误?嵌套的 if-else 结构是否正确排序?
- c - 如何从汇编代码构建数据依赖图
- java - 使用带有随机枢轴的快速选择的第 K 个最小元素
- javascript - javascript externe 类或数组对 onmessage 工作者可见
- objective-c - 在 Xcode 中找不到 -lProtobuf 的库
- cmake - CMake:使用转义字符获取环境变量
- php - 尽管在包的 Github 分支中有标签,但在作曲家中得到“找不到包的版本..”
- react-native - 如何在 React Native 上制作 ActionBar?
- .net-core - 带有 .NET Core 3.0 的 ServiceStack 5 似乎不起作用