我尝试了一些解决方案,但没有成功。我想知道是否有一个解决方案,最好有一个易于理解的教程。
答案 0 :(得分:64)
您有三种选择:
这是一个简单的库,用于保持iFrames的内容大小。它使用PostMessage和MutationObserver API,以及IE8-10的后备。它还有内容页面的选项,可以请求包含iFrame的特定大小,也可以在完成后关闭iFrame。
https://github.com/davidjbradshaw/iframe-resizer
Easy XDM使用一系列技巧在多个浏览器中启用不同窗口之间的跨域通信,并且有一些示例可用于iframe大小调整:
http://easyxdm.net/wp/2010/03/17/resize-iframe-based-on-content/
http://kinsey.no/blog/index.php/2010/02/19/resizing-iframes-using-easyxdm/
Easy XDM使用现代浏览器上的PostMessage和基于Flash的解决方案作为旧版浏览器的后备功能。
另见this thread on Stackoverflow(还有其他人,这是一个常见问题)。另外,Facebook would seem to use a similar approach。
另一种选择是将iframe高度发送到您的服务器,然后使用JSONP从父网页上从该服务器进行轮询(或者如果可能的话,使用长轮询)。
答案 1 :(得分:21)
我得到了根据内容动态设置iframe高度的解决方案。这适用于跨域内容。 要实现这一目标,需要遵循一些步骤。
假设您已在" abc.com/page"中添加了iframe。网页
<div>
<iframe id="IframeId" src="http://xyz.pqr/contactpage" style="width:100%;" onload="setIframeHeight(this)"></iframe>
</div>
接下来你必须绑定windows&#34; message&#34;网页下的活动&#34; abc.com/page"
window.addEventListener('message', function (event) {
//Here We have to check content of the message event for safety purpose
//event data contains message sent from page added in iframe as shown in step 3
if (event.data.hasOwnProperty("FrameHeight")) {
//Set height of the Iframe
$("#IframeId").css("height", event.data.FrameHeight);
}
});
On iframe load you have to send message to iframe window content with "FrameHeight" message
function setIframeHeight(ifrm) {
var height = ifrm.contentWindow.postMessage("FrameHeight", "*");
}
&#13;
window.addEventListener('message', function (event) {
// Need to check for safty as we are going to process only our messages
// So Check whether event with data(which contains any object) contains our message here its "FrameHeight"
if (event.data == "FrameHeight") {
//event.source contains parent page window object
//which we are going to use to send message back to main page here "abc.com/page"
//parentSourceWindow = event.source;
//Calculate the maximum height of the page
var body = document.body, html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
// Send height back to parent page "abc.com/page"
event.source.postMessage({ "FrameHeight": height }, "*");
}
});
&#13;
最后,您的iframe高度将在iframe加载时设置。
快乐的编码!!!
答案 2 :(得分:14)
我做的是比较iframe scrollWidth,直到它改变大小,同时我逐步设置IFrame高度。它对我来说很好。您可以将增量调整为所需的值。
<script type="text/javascript">
function AdjustIFrame(id) {
var frame = document.getElementById(id);
var maxW = frame.scrollWidth;
var minW = maxW;
var FrameH = 100; //IFrame starting height
frame.style.height = FrameH + "px"
while (minW == maxW) {
FrameH = FrameH + 100; //Increment
frame.style.height = FrameH + "px";
minW = frame.scrollWidth;
}
}
</script>
<iframe id="RefFrame" onload="AdjustIFrame('RefFrame');" class="RefFrame"
src="http://www.YourUrl.com"></iframe>
答案 3 :(得分:1)
这是我在此页面上的简单解决方案。 http://lab.ohshiftlabs.com/iframesize/
以下是它的工作原理;
基本上,如果您能够在其他域编辑页面,则可以放置另一个属于您的服务器的iframe页面,以便将高度保存到cookie。 使用间隔读取Cookie时更新,更新iframe的高度。就是这样。
下载; http://lab.ohshiftlabs.com/iframesize/iframesizepost.zip
答案 4 :(得分:0)
我找到了另一个使用PHP来获取iframe大小的Web开发服务器端解决方案。
首先是通过内部函数将服务器脚本PHP用于外部调用:(如file_get_contents
但有curl和dom)。
function curl_get_file_contents($url,$proxyActivation=false) {
global $proxy;
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
curl_setopt($c, CURLOPT_REFERER, $url);
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
if($proxyActivation) {
curl_setopt($c, CURLOPT_PROXY, $proxy);
}
$contents = curl_exec($c);
curl_close($c);
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
@$dom->loadHTML($contents);
$form = $dom->getElementsByTagName("body")->item(0);
if ($contents) //si on a du contenu
return $dom->saveHTML();
else
return FALSE;
}
$url = "http://www.google.com"; //Exernal url test to iframe
<html>
<head>
<script type="text/javascript">
</script>
<style type="text/css">
#iframe_reserve {
width: 560px;
height: 228px
}
</style>
</head>
<body>
<div id="iframe_reserve"><?php echo curl_get_file_contents($url); ?></div>
<iframe id="myiframe" src="http://www.google.com" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" style="overflow:none; width:100%; display:none"></iframe>
<script type="text/javascript">
window.onload = function(){
document.getElementById("iframe_reserve").style.display = "block";
var divHeight = document.getElementById("iframe_reserve").clientHeight;
document.getElementById("iframe_reserve").style.display = "none";
document.getElementById("myiframe").style.display = "block";
document.getElementById("myiframe").style.height = divHeight;
alert(divHeight);
};
</script>
</body>
</html>
您需要在div(iframe_reserve
)下显示函数调用生成的html,方法是使用简单的echo curl_get_file_contents("location url iframe","activation proxy")
执行此操作后,使用javascript取得身体事件函数onload取得页面iframe的高度,只需简单控制内容div(iframe_reserve
)
所以我使用divHeight = document.getElementById("iframe_reserve").clientHeight;
来获取屏蔽div容器(iframe_reserve
)之后要调用的外部页面的高度。在此之后,我们加载iframe的高度就好了。
答案 5 :(得分:0)
我有一个脚本,它在iframe中包含了内容。它还确保iFrameResizer存在(它将其作为脚本注入),然后进行大小调整。
我将在下面简单介绍一下。
// /js/embed-iframe-content.js
(function(){
// Note the id, we need to set this correctly on the script tag responsible for
// requesting this file.
var me = document.getElementById('my-iframe-content-loader-script-tag');
function loadIFrame() {
var ifrm = document.createElement('iframe');
ifrm.id = 'my-iframe-identifier';
ifrm.setAttribute('src', 'http://www.google.com');
ifrm.style.width = '100%';
ifrm.style.border = 0;
// we initially hide the iframe to avoid seeing the iframe resizing
ifrm.style.opacity = 0;
ifrm.onload = function () {
// this will resize our iframe
iFrameResize({ log: true }, '#my-iframe-identifier');
// make our iframe visible
ifrm.style.opacity = 1;
};
me.insertAdjacentElement('afterend', ifrm);
}
if (!window.iFrameResize) {
// We first need to ensure we inject the js required to resize our iframe.
var resizerScriptTag = document.createElement('script');
resizerScriptTag.type = 'text/javascript';
// IMPORTANT: insert the script tag before attaching the onload and setting the src.
me.insertAdjacentElement('afterend', ifrm);
// IMPORTANT: attach the onload before setting the src.
resizerScriptTag.onload = loadIFrame;
// This a CDN resource to get the iFrameResizer code.
// NOTE: You must have the below "coupled" script hosted by the content that
// is loaded within the iframe:
// https://unpkg.com/iframe-resizer@3.5.14/js/iframeResizer.contentWindow.min.js
resizerScriptTag.src = 'https://unpkg.com/iframe-resizer@3.5.14/js/iframeResizer.min.js';
} else {
// Cool, the iFrameResizer exists so we can just load our iframe.
loadIFrame();
}
}())
然后可以使用如下脚本将iframe内容注入到另一个页面/站点中的任何位置:
<script
id="my-iframe-content-loader-script-tag"
type="text/javascript"
src="/js/embed-iframe-content.js"
></script>
iframe内容将在您放置脚本标记的任何位置注入。
希望这对某人有帮助。
答案 6 :(得分:0)
在工作中(使用React)时,我遇到了这个问题。基本上,我们有一些外部html内容,我们将它们保存到数据库的文档表中,然后在某些情况下(当您位于Documents数据集中时)插入页面中。
因此,给定n
内联,其中最多n
可以包含外部html,我们需要设计一个系统,以在每个内联中的内容完全加载后自动调整每个内联的iframe的大小。在转动了一下轮子之后,这就是我最终要做的事情:
message
事件侦听器,该事件侦听器将检查要从发送方iframe设置的特定密钥。<script>
标签,该标签将等待iframe的window.onload
触发。一旦触发,我们就使用postMessage
将有关iframe ID,计算出的高度等信息发送到父窗口。id
对象中传递的iframe的DOM MessageEvent
iframe
,只需将iframe postMessage
传递的值设置为高度即可。// index
if (window.postMessage) {
window.addEventListener("message", (messageEvent) => {
if (
messageEvent.data.origin &&
messageEvent.data.origin === "company-name-iframe"
) {
const iframe = document.getElementById(messageEvent.data.id)
// this is the only way to ensure that the height of the iframe container matches its body height
iframe.style.height = `${messageEvent.data.height}px`
// by default, the iframe will not expand to fill the width of its parent
iframe.style.width = "100%"
// the iframe should take precedence over all pointer events of its immediate parent
// (you can still click around the iframe to segue, for example, but all content of the iframe
// will act like it has been directly inserted into the DOM)
iframe.style.pointerEvents = "all"
// by default, iframes have an ugly web-1.0 border
iframe.style.border = "none"
}
})
}
// in component that renders n iframes
<iframe
id={`${props.id}-iframe`}
src={(() => {
const html = [`data:text/html,${encodeURIComponent(props.thirdLineData)}`]
if (window.parent.postMessage) {
html.push(
`
<script>
window.onload = function(event) {
window.parent.postMessage(
{
height: document.body.scrollHeight,
id: "${props.id}-iframe",
origin: "company-name-iframe",
},
"${window.location.origin}"
);
};
</script>
`
)
}
return html.join("\n")
})()}
onLoad={(event) => {
// if the browser does not enforce a cross-origin policy,
// then just access the height directly instead
try {
const { target } = event
const contentDocument = (
target.contentDocument ||
// Earlier versions of IE or IE8+ where !DOCTYPE is not specified
target.contentWindow.document
)
if (contentDocument) {
target.style.height = `${contentDocument.body.scrollHeight}px`
}
} catch (error) {
const expectedError = (
`Blocked a frame with origin "${window.location.origin}" ` +
`from accessing a cross-origin frame.`
)
if (error.message !== expectedError) {
/* eslint-disable no-console */
console.err(
`An error (${error.message}) ocurred while trying to check to see ` +
"if the inner iframe is accessible or not depending " +
"on the browser cross-origin policy"
)
}
}
}}
/>